微信小程序——多张图片上传(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后台,注释应该比较清楚了,就不再解释了:

@Controller
public 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());

        //裁剪用户id
        String 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;
    }
}

小程序端选择了文件:

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

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

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

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

 

 

你可能感兴趣的:(微信小程序——多张图片上传(uploadFile) Java后台)