微信小程序图片上传与pc端图片上传是不同的,话不多说直接上代码:(复制粘贴可用)
微信小程序端:
chooseImage(){
wx.chooseImage({
success: function (res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://127.0.0.1:8888/pesss/weChat/uploadImage.do',
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success: function (res) {
var data = res.data
//do something
},fail:function(err){
console.log(err)
}
})
}
})
}
后端代码
/**
* 直播间图片上传
* @param request
* @param response
* @return
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping(value = "/uploadImage", method = { RequestMethod.POST,RequestMethod.GET})
public void weChatImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("进入get方法!");
MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
MultipartFile multipartFile = req.getFile("uploadfile_ant"); //对应前端页面的name值
String path=request.getSession().getServletContext().getRealPath("/image/");
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
//生成一个新的文件名fileName
String n=UUID.randomUUID().toString().substring(0, 11);
String picName =n + "."+ "jpg";
String d="/image/"+picName;
File file = new File(path,picName);
multipartFile.transferTo(file);
//返回图片名
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(d));
printWriter.flush();
}
注意:1.加粗的地方要与前端对应上
2.返回文件路径时:用阿里巴巴的jsonobject与net.sf.json.JSONObject, 返回会报错,所以只能用response