前台代码:

bindPhoto(e) {
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original','compressed'],// 指定原图或者压缩图
sourceType: ['album', 'camera'], // 指定图片来源
success: function (res) {
var tempFilePaths = res.tempFilePaths;
wx.uploadFile({
url: 'http://192.168.31.111:8007/goods/wx_upload.do',
filePath: tempFilePaths[0],
name: 'file',
header: { "Content-Type": "multipart/form-data" },
formData:{
'session_token': token
},
success:function(res){
var cur_data = res.data;
console.log(cur_data.fileName);
 
},
fail: function (res) {
console.log('上传失败');
}
})
}
})
},
后台代码
/*微信小程序上传图片测试*/
@RequestMapping("wx_upload.do")
public void wx_upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8"); //设置编码
//获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String fileId = null;
String json = "{\"success\":false,\"fileName\":\"" + fileId + "\"}";
String pathUrl = FSDefaultMgr.E_DEFAULT.getDefaultUploadPathUrl();//获取图片服务器路径
InputStream inStream = null;
try {
//可以上传多个文件
List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
for(FileItem item : list){
//获取表单的属性名字
String name = item.getFieldName();
//如果获取的 表单信息是普通的 文本 信息
if(item.isFormField()){
//获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
String value = item.getString() ;
request.setAttribute(name, value);
}else {
//获取路径名
String filename = item.getName();
request.setAttribute(name, filename);
inStream = item.getInputStream() ;
}
}
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] bytes = swapStream.toByteArray();
fileId = FastDFSClient.uploadFile(bytes, "20161545454.png", null);
if (fileId != null) {
json = "{\"success\":true,\"pathUrl\":\"" + pathUrl + "\",\"fileName\":\"" + fileId + "\"}";
}
response.getWriter().write(json);
response.getWriter().flush();
response.getWriter().close();
}catch (Exception e) {
e.printStackTrace();
}
} 当使用的是springMVC框架时:

SpringMVC中servletFileUpload.parseRequest(request)解析为空获取不到数据问题

原因分析

首先我们来看下Spring mvc 中文件上传的配置


  1. <bean id="multipartResolver"
  2. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  3. <property name="defaultEncoding" value="UTF-8" />
  4. <property name="maxUploadSize" value="2000000000" />
  5. </bean>

再来看看Controller中使用

  1. public void upload2(HttpServletRequest request) {
  2. // 转型为MultipartHttpRequest
  3. try {
  4. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  5. List<MultipartFile> fileList = multipartRequest.getFiles("file");
  6. for (MultipartFile mf : fileList) {
  7. if(!mf.isEmpty()){
  8. }
  9. }
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }

方式二

  1. public String upload(HttpServletRequest request,
  2. @RequestParam(value = "file") MultipartFile[] files) {
  3. try {
  4. for (MultipartFile mf : files) {
  5. if(!mf.isEmpty()){
  6. }
  7. }
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. return "upload";
  12. }
  1. 这里springMVC 都为我们封装好成自己的文件对象了,转换的过程就在我们所配置的CommonsMultipartResolver这个转换器里面下面再来看看它的源码

他的转换器里面就是调用common-fileupload的方式解析,然后再使用parseFileItems()方法封装成自己的文件对象 .

List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);

大家应该发现了上面的这句代码,已经使用过fileUpload解析过request了,你在Controller里面接收到的request都已经是解析过的,你再次使用upload进行解析获取到的肯定是空,这个就是问题的所在(大家可以在servlet里面实验,看看第二次解析后能不能获取到数据,当然是不能的)

解决方案

1)删除Spring MVC文件上传配置

  1. <!--
  2. <bean id="multipartResolver"
  3. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  4. <property name="defaultEncoding" value="UTF-8" />
  5. <property name="maxUploadSize" value="2000000000" />
  6. </bean>
  7. -->
在控制器里面自己完成request的解析(当然上面spring MVC提供的两种方法是不能用的,所有上传的地方都需要自己做处理)
  1. public void upload3(HttpServletRequest request) {
  2. DiskFileItemFactory factory = new DiskFileItemFactory();
  3. ServletFileUpload upload = new ServletFileUpload(factory);
  4. try {
  5. List<FileItem> list = upload.parseRequest(request);
  6. for(FileItem item : list){
  7. if(item.isFormField()){
  8. }else{
  9. //item.write(new File(""));
  10. }
  11. }
  12. } catch (FileUploadException e) {
  13. e.printStackTrace();
  14. }
  15. }
2)如果是需要使用的ProgressListener监听器我们可以重写 CommonsMultipartResolver的parseRequest方法
  1. package com.lwp.spring.ext;
  2. import java.util.List;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.commons.fileupload.FileItem;
  5. import org.apache.commons.fileupload.FileUpload;
  6. import org.apache.commons.fileupload.FileUploadBase;
  7. import org.apache.commons.fileupload.FileUploadException;
  8. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  9. import org.springframework.web.multipart.MaxUploadSizeExceededException;
  10. import org.springframework.web.multipart.MultipartException;
  11. import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  12. import com.lwp.listener.FileUploadListener;
  13. public class CommonsMultipartResolverExt extends CommonsMultipartResolver {
  14. @Override
  15. protected MultipartParsingResult parseRequest(HttpServletRequest request)
  16. throws MultipartException {
  17. FileUploadListener listener = new FileUploadListener();
  18. String encoding = determineEncoding(request);
  19. FileUpload fileUpload = prepareFileUpload(encoding);
  20. fileUpload.setProgressListener(listener);
  21. try {
  22. List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
  23. return parseFileItems(fileItems, encoding);
  24. }
  25. catch (FileUploadBase.SizeLimitExceededException ex) {
  26. throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
  27. }
  28. catch (FileUploadException ex) {
  29. throw new MultipartException("Could not parse multipart servlet request", ex);
  30. }
  31. }
  32. }

监听器方法

  1. import org.apache.commons.fileupload.ProgressListener;
  2. public class FileUploadListener implements ProgressListener {
  3. @Override
  4. public void update(long arg0, long arg1, int arg2) {
  5. //arg0 已经上传多少字节
  6. //arg1 一共多少字节
  7. //arg2 正在上传第几个文件
  8. System.out.println(arg0 +"\t" + arg1 +"\t" + arg2);
  9. }
  10. }

配置文件改为我们自己的(这种方式的缺陷是,所有文件上传都需要使用到Listener)

  1. <bean id="multipartResolver"
  2. class="com.lwp.spring.ext.CommonsMultipartResolverExt">
  3. <property name="defaultEncoding" value="UTF-8" />
  4. <property name="maxUploadSize" value="2000000000" />
  5. </bean>

注: 综上所述,如果只是普通的文件上传spring MVC 完全可以完成,如果需要使用进度条的listener前段可以使用假的进度条或者是上面的两种方式.

小程序文件上传uploadFile的更多相关文章

  1. 微信小程序文件上传结合lin ul

    html <l-form name="goods" l-form-btn-class="l-form-btn-class" bind:linsubmit= ...

  2. 微信小程序文件上传至七牛云(laravel7)

    1 wxml: <view> <form bindsubmit="dopost"> <view> <label>真实姓名</l ...

  3. 小程序--->小程序图片上传阿里OSS使用方法

    小程序图片上传阿里OSS使用方法 首先看下参考文档 ( http://blog.csdn.net/qq_38125123/article/details/73870667) 这里只将一些运用过程中遇到 ...

  4. (SSM框架)实现小程序图片上传(配小程序源码)

    阅读本文约"2分钟" 又是一个开源小组件啦! 因为刚好做到这个小功能,所以就整理了一下,针对微信小程序的图片(文件)上传! 原业务是针对用户反馈的图片上传.(没错,本次还提供小程序 ...

  5. 微信小程序图片上传并展示

    1.首先编写微信小程序的页面和样式: index.js var total = []; Page({ data: { perImgSrc: [] }, onLoad: function (option ...

  6. 转:【专题十一】实现一个基于FTP协议的程序——文件上传下载器

    引言: 在这个专题将为大家揭开下FTP这个协议的面纱,其实学习知识和生活中的例子都是很相通的,就拿这个专题来说,要了解FTP协议然后根据FTP协议实现一个文件下载器,就和和追MM是差不多的过程的,相信 ...

  7. 专题十一:实现一个基于FTP协议的程序——文件上传下载器

    引言: 在这个专题将为大家揭开下FTP这个协议的面纱,其实学习知识和生活中的例子都是很相通的,就拿这个专题来说,要了解FTP协议然后根据FTP协议实现一个文件下载器,就和和追MM是差不多的过程的,相信 ...

  8. 5行代码实现微信小程序图片上传与腾讯免费5G存储空间的使用

    本文介绍了如何在微信小程序开发中使用腾讯官方提供的云开发功能快速实现图片的上传与存储,以及介绍云开发的 5G 存储空间的基本使用方法,这将大大提高微信小程序的开发效率,同时也是微信小程序系列教程的视频 ...

  9. 快速高效实现微信小程序图片上传与腾讯免费5G存储空间的使用

    本文介绍了如何在微信小程序开发中使用腾讯官方提供的云开发功能快速实现图片的上传与存储,以及介绍云开发的 5G 存储空间的基本使用方法,这将大大提高微信小程序的开发效率 对于一般的图片上传功能开发,我们 ...

随机推荐

  1. Zookeeper服务器配置项详解

    文章转自: http://www.bug315.com/article/159.htm http://www.bug315.com/article/160.htm Zookeeper是通过一个***. ...

  2. Vue(一):简介和安装

    概况 Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的渐进式框架. Vue 只关注视图层, 采用自底向上增量开发的设计. Vue 的目标是通过尽可能简单的 API 实现响应 ...

  3. MYSQL MVCC实现及其机制

    多版本并发控制 Multiversion Concurrency Control 大部分的MySQL的存储 引擎,比如InnoDB,Falcon,以及PBXT并不是简简单单的使用行锁机制.它们都使用了 ...

  4. 移动网络应用开发中,使用 HTTP 协议比起使用 socket 实现基于 TCP 的自定义协议有哪些优势?

    HTTP 是应用层协议,TCP 是传输层协议(位于应用层之下),放在一起类比并不合适.不过猜测楼主是想对比 “标准 HTTP 协议” 还是 “自定义的协议(基于 TCP Socket)” . 一般来说 ...

  5. 关于的 recorder robotium 的Eclipse插件(URL:http://recorder.robotium.com/updates/或者说不可用)

    最近在学robotium.看到别人说robotium的Eclipse的插件非常好用. 打算安装时.发现死活都无法连接http://recorder.robotium.com/updates/ 过程是  ...

  6. sql中计算某天是全年的第几周及取得某天的所在周的周一的日期的函数

    --取得某天的所在周的周一的函数 CREATE FUNCTION getMondayBtDate(@date datetime) RETURNS date AS begin DECLARE @week ...

  7. JAVA中转义字符

    JAVA中转义字符 2010年08月11日 星期三 上午 12:22 JAVA中转义字符: 1.八进制转义序列:\ + 1到3位5数字:范围'\000'~'\377'       \0:空字符 2.U ...

  8. 每日英语:The Most Destructive, Unpredictable Force in Tech

    What's the most destructive force in the tech world, the thing that has nearly killed BlackBerry, pu ...

  9. 【Linux技术】linux库文件编写·入门

    一.为什么要使用库文件 我们在实际编程中肯定会遇到这种情况:有几个项目里有一些函数模块的功能相同,实现代码也相同,也是我们所说的重复代码.比如,很多项目里都有一个用户验证的功能. 代码段如下: //U ...

  10. python中 staticmethod与classmethod区别

    staticmethod与classmethod区别 参考 https://stackoverflow.com/questions/136097/what-is-the-difference-betw ...