600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 微信小程序——多张图片上传(uploadFile) Java后台

微信小程序——多张图片上传(uploadFile) Java后台

时间:2019-08-25 01:46:28

相关推荐

微信小程序——多张图片上传(uploadFile) Java后台

首先是前端js的代码:

Page({data: {},//选择并上传图片--Max:9张selectImage: function () {wx.chooseImage({count: 9,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],success: function (res) {//将图片路径循环赋值给filePath参数for (var i = 0; i < res.tempFilePaths.length; i++) {var imgUrl = res.tempFilePaths[i];wx.uploadFile({//上传图片的网路请求地址url: 'http://localhost:8080//upload/uploadPic',//选择filePath: imgUrl,name: 'file',success: function (res) {console.log("success");},fail: function (res) {console.log("error");}});}//for循环结束}});console.log("****正在添加图片*****");},})

然后是Java后台,注释应该比较清楚了,就不再解释了:

@Controllerpublic class uploadPicture {@RequestMapping(value = "/upload/uploadPic", method = {RequestMethod.POST, RequestMethod.GET})public ModelAndView uploadPicture(HttpServletRequest request, HttpServletResponse response) throws IOException {MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;//对应前端的upload的name参数"file"MultipartFile multipartFile = req.getFile("file");//realPath填写电脑文件夹路径String realPath = "C:\\Users\\Admin\\Pictures\\WeChatPic";//格式化时间戳SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");String nowTime = sdf.format(new Date().getTime());//裁剪用户idString originalFirstName = multipartFile.getOriginalFilename();String picFirstName = originalFirstName.substring(0, originalFirstName.indexOf("."));//取得图片的格式后缀String originalLastName = multipartFile.getOriginalFilename();String picLastName = originalLastName.substring(originalLastName.lastIndexOf("."));//拼接:名字+时间戳+后缀String picName = picFirstName + "." + nowTime + picLastName;try {File dir = new File(realPath);//如果文件目录不存在,创建文件目录if (!dir.exists()) {dir.mkdir();System.out.println("创建文件目录成功:" + realPath);}File file = new File(realPath, picName);multipartFile.transferTo(file);System.out.println("添加图片成功!");} catch (IOException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();}return null;}}

小程序端选择了文件:

后端操作完成后,相应路径也能看到文件成功上传:

成功实现了小程序上传图片的功能。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。