安装插件:

import { Camera, Transfer } from 'ionic-native';

TS代码:


  uploadFile(element, callbackType?: any, skip?: string) {
    this.nativeService.showLoading(element.name + '文件正在上传', true);
    const fileTransfer = new Transfer();
    /**
       * 上传文件时携带参数,这个是可选项。
       */
    var options: any;
    var reqUri = GLOBAL_CONST.APP_SERVE_URL + "/bfs/bfs/fileup/appuploadfile";
    options = {
      fileKey: 'files',
      fileName: element.name,
      mimeType: this.getMimeType(element.type),
      params: {
        docID: this.item.docId,
        fileName: element.name,
        fileType: element.fileType,
        takeTime: element.takeTime,
        takeUserId: GLOBAL_CONST.USER_INFO['userID'],
        takeUserName: element.takeUserName,
        takeLongitude: element.takeLongitude,
        takeLatitude: element.takeLatitude
      },

      headers: { sid: GLOBAL_CONST.USER_INFO['token'] }
    }
    
    this.evidenceList.splice(0, 1);
    //第一个参数是文件的路径,第二个参数是服务器的url,第二个参数也可以是encodeURI(reqUri)
    fileTransfer.upload(element.path, reqUri, options).then((data) => {
      alert(JSON.stringify(data));
      let dataValue  = data.response;
      let dataObject: any = JSON.parse(dataValue);
      if(dataObject.success){
        alert(dataObject.fileid);
        this.fileList.push(dataObject.fileid);
      }

      this.nativeService.hideLoading();

      if (this.evidenceList.length == 0) {
          this.submitAddForm();
      }
      for (let idx in this.evidenceList) {
        this.uploadFile(this.evidenceList[idx], callbackType, skip);
        break;
      }

    }, (err) => {
      this.nativeService.hideLoading();

      if (this.evidenceList.length == 0) {
        this.submitAddForm();
      }

      for (let idx in this.evidenceList) {
        this.uploadFile(this.evidenceList[idx], callbackType, skip);
        break;
      }

    });
  }
后台代码:



/**
	 * 
	 * appUploadFile:APP文件上传
	 * 
	 * @param files 上传文件裂变
	 * @param data 预留data数据
	 * @throws Exception void
	 * 
	 * 追加时间:2017年10月23日14:13:14
	 * 追加人:DingXiangGuang
	 */
	@ResponseBody
	@SuppressWarnings("unused")
	@RequestMapping(value = "/appuploadfile", method = RequestMethod.POST)
	public void appUploadFile(@RequestParam("files") MultipartFile[] files) throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		String path = "";
		PrintWriter writer = null;
		String orgfilename = "";

		try {
			Properties pro = new Properties();
			pro.load(FileUpController.class.getResourceAsStream("/file.properties"));
			DiskFileItemFactory factory = new DiskFileItemFactory();
			String filepath = pro.getProperty("path");
			path = request.getSession().getServletContext().getRealPath("/")+ "App_"+filepath;
			factory.setRepository(new File(path));
			factory.setSizeThreshold(1024 * 1024);		
			for (Integer i = 0; i < files.length; i++) {
					orgfilename = files[i].getOriginalFilename(); // 传入名称
					String extname = orgfilename.substring(orgfilename.lastIndexOf(".") + 1, orgfilename.length()); //图片后缀
					String fileName = UUID.randomUUID().toString().replaceAll("-", ""); //图片当前名称
					String serverfilename = fileName + "." + extname; //服务器保存的图片名称
					File headPath = new File(path);// 获取文件夹路径
					if (!headPath.exists()) {// 判断文件夹是否创建,没有创建则创建新文件夹
						headPath.mkdirs();
					}
					OutputStream out = new FileOutputStream(new File(path, serverfilename));
					InputStream in = files[i].getInputStream();
					int filesize = in.available();
					int length = 0;
					byte[] buf = new byte[1024];
					while ((length = in.read(buf)) != -1) {
						out.write(buf, 0, length);
					}
					in.close();
					out.close();
					/** 将上传处理后的数据返回 **/
					map.put("orgfilename", orgfilename);
					map.put("filepath", (filepath + "\\" + serverfilename));

					FileInfoVO fiv = new FileInfoVO();
					fiv.setOrgfilename(orgfilename);
					fiv.setServerfilename(serverfilename);
					fiv.setFilepath(filepath + "\\" + serverfilename);
					fiv.setFilesize(new Double(filesize));
					fiv.setExtname(extname);
					fiv.setCtime(new Date());
					fileInfoService.insertSelective(fiv);
					map.put("fileid", fiv.getFileid());
					map.put("success", "true");
					break;
				}
			response.setContentType("text/xml; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "no-cache");
			writer = this.response.getWriter();
			String msg = JSON.toJSONString(map);
			writer.print(msg);

		} catch (Exception e) {
			logger.error("上传文件出错:" + e);
			map.put("success", "false");
			map.put("orgfilename", orgfilename);
			map.put("filepath", path);
			map.put("error", e.getMessage());
			String msg = JSON.toJSONString(map);
			if (writer == null) {
				writer = this.response.getWriter();
			}
			writer.print(msg);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
Spring-MVC配置:



	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8"></property>
		<property name="maxUploadSize" value="10485760000"></property>
		<property name="maxInMemorySize" value="40960"></property>
	</bean>



欢迎留言