微信小程序——多张图片上传(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;
    }
}

小程序端选择了文件:

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

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

 

 

  • 5
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 22
    评论
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值