
前言
最近在做微信小程序开发,用到了通过微信小程序上传图片到服务器的一个功能,下面分享给大家。
小程序端
chooseImage: function () {
var openid = wx.getStorageSync("openid");
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
console.log(tempFilePaths[0]);
wx.uploadFile({
url: app.globalData.mainServer + 'ApiController/uploadImgFile.do', //此处换上你的接口地址
filePath: tempFilePaths[0],
name: 'img',
header: {
"Content-Type": "multipart/form-data",
'accept': 'application/json'
},
formData: {},
success: function (res) {
console.log(res)
var data = JSON.parse(res.data)[0].info;
data = data.replace(app.globalData.mainServer,'');
that.setData({
picUrl:data
})
},
fail: function (res) {
console.log('fail');
},
})
}
})
}
说明:上面代码中app.globalData.mainServer是接口调用地址的前缀,res.data.info存储的是已经上传的图片的网络地址,包含域名部分。
服务端Java处理代码
@RequestMapping(value="/uploadImgFile.do",method={RequestMethod.GET,RequestMethod.POST})
public String uploadImgFile(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
Map<String,Object> m = new HashMap<String,Object>();
JSONArray resultJson = new JSONArray();
String mainServer = this.apiService.findValueByNameAdmin("mainServer", "admin");
MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
MultipartFile multipartFile = req.getFile("img");
String realPath = request.getServletContext().getRealPath("/upload/");
String imgName =UUID.randomUUID().toString()+".jpg";
String imgPath = mainServer+"upload/"+imgName;
try {
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(realPath,imgName);
multipartFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
m.put("info", imgPath);
JsonConfig config = new JsonConfig();
JsonDateValueProcessor jsonValueProcessor = new JsonDateValueProcessor();
config.registerJsonValueProcessor(Date.class, jsonValueProcessor);
resultJson = JSONArray.fromObject(m,config);
try
{
BufferedWriter out = null;
out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
out.write(resultJson.toString());
out.flush();
}
catch (IOException e){
e.printStackTrace();
}
return null;
}














