您的位置:首页 > 移动开发 > 微信开发

微信小程序开发之图片上传+Java服务端接收

2017-09-02 00:07 706 查看
闲言少叙直入正题

前端代码在网上一搜一大堆,且搜出来的结果基本上是正确的,没啥好说的,我连代码都不想贴(如果有时间的话明天整理下贴在文章结尾,没时间的话就不贴了)。但是,但是,但是,靠谱的,不用改动就能够正常运行的Java服务端接收代码,几乎没有,没错,是几乎,没有。因为我基本上把网上能搜出来的代码都试了。试到第三个的时候,有点靠谱了,遗憾的是有bug。所幸改了bug后,代码正常运行无误。所以现在将服务端代码贴在这里,造福后人。

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
* Created by majl on 2017/9/1.
*/
@Controller
@RequestMapping("/upload")
public class UploadController {
private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

@RequestMapping("/picture")
public void uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
//获取文件需要上传到的路径
String path = request.getRealPath("/upload") + "/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
logger.debug("path=" + path);

request.setCharacterEncoding("utf-8");  //设置编码
//获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();

//如果没以下两行设置的话,上传大的文件会占用很多内存,
//设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
/**
* 原理: 它是先存到暂时存储室,然后再真正写到对应目录的硬盘上,
* 按理来说当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
* 然后再将其真正写到对应目录的硬盘上
*/
factory.setRepository(dir);
//设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室
factory.setSizeThreshold(1024 * 1024);
//高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> list = upload.parseRequest(request);
FileItem picture = null;
for (FileItem item : list) {
//获取表单的属性名字
String name = item.getFieldName();
//如果获取的表单信息是普通的 文本 信息
if (item.isFormField()) {
//获取用户具体输入的字符串
String value = item.getString();
request.setAttribute(name, value);
logger.debug("name=" + name + ",value=" + value);
} else {
picture = item;
}
}

//自定义上传图片的名字为userId.jpg
String fileName = request.getAttribute("userId") + ".jpg";
String destPath = path + fileName;
logger.debug("destPath=" + destPath);

//真正写到磁盘上
File file = new File(destPath);
OutputStream out = new FileOutputStream(file);
InputStream in = picture.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
// in.read(buf) 每次读到的数据存放在buf 数组中
while ((length = in.read(buf)) != -1) {
//在buf数组中取出数据写到(输出流)磁盘上
out.write(buf, 0, length);
}
in.close();
out.close();
} catch (FileUploadException e1) {
logger.error("", e1);
} catch (Exception e) {
logger.error("", e);
}

PrintWriter printWriter = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
HashMap<String, Object> res = new HashMap<String, Object>();
res.put("success", true);
printWriter.write(JSON.toJSONString(res));
printWriter.flush();
}


拍着胸脯保证,这代码你拷贝下去就能用,而且还不要求你用什么框架(我这里因为项目本身用了spring,我只是用了它的RequestMapping,但是上传逻辑本身,是和spring无关的)。

解释一下:

1.String path = request.getRealPath(“/upload”) + “/”;

这个是图片的存放路径,根据打印的信息可以看到,upload目录就建在根目录下。

2.微信小程序上传的图片文件名都是wx-file.jpg,我这里取了从前端传过来的userId为文件命名。userId需要放在wx.uploadFile的formData中。

撒花,搞定。

由于微信小程序上传图片api要求只能是HTTPS POST请求,而本地是不支持HTTPS的,所以调试的时候颇费了周折。还好,搞定了。感谢CCAV,感谢老公,感谢自己。

晚安。

附上微信小程序的代码

注意设置header

wx.uploadFile({
url: 'https://xxxxxx/upload/picture',
filePath: filePath,//图片路径,如tempFilePaths[0]
name: 'image',
header : {
"Content-Type": "multipart/form-data"
},
formData:
{
userId: 12345678 //附加信息为用户ID
},
success: function (res) {
console.log(res);
},
fail: function (res) {
console.log(res);
},
complete: function (res) {

}
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息