最近在做微信小程序图片上传,将代码上传,造福后来人,废话不多说,贴代码:
微信小程序端
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) } }) } }) }
java 端:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; @Controller public class ImageTestWebchatController { @RequestMapping(value = "/weChat/uploadImage", method = { RequestMethod.POST,RequestMethod.GET}) public ModelAndView uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("进入get方法!"); MultipartHttpServletRequest req =(MultipartHttpServletRequest)request; MultipartFile multipartFile = req.getFile("file"); String realPath = "F:/image"; try { File dir = new File(realPath); if (!dir.exists()) { dir.mkdir(); } File file = new File(realPath,"aaa.jpg"); multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } return null; } }
Java端的返回参数就自己拼写吧,文件路径、名称可以自行命名 ,因为是测试,这里就不写全了。
如有问题,请加入微信小程序开发群:563752274,答案:Tony