Small program image upload function

Applet code:

UpImages.wxml

<button bindtap='uploadPhoto'>拍照选取照片上传</button>

 Simply draw a page, use the button to adjust the default upload (page, path) method of the applet, the default supports a single upload of a picture, which can be modified

 Upimages.js

Page({
  data: {
    imgData: []
  },
  uploadPhoto() { // 拍摄或从相册选取上传
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success(res) {
        let tempFilePaths = res.tempFilePaths; // 返回选定照片的本地路径列表 
        that.upload(that, tempFilePaths);
      }
    })
  },
  
  upload(page, path) { // 上传图片
    wx.showToast({
      icon: "loading",
      title: "正在上传……"
    });
    wx.uploadFile({
      url: '', //本地后端接口
      filePath: path[0],
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"   //必须是multipart/form-data格式才能上传文件
      },
      formData: {
        //和服务器约定的token, 一般也可以放在header中
        'session_token': wx.getStorageSync('session_token')
        },
      success(res) {
        console.log(res)
        if (res.statusCode != 200) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          });
          return;
        } else {
          wx.showModal({
            title: '提示',
            content: '上传成功',
            success: function (res) {
              if (res.confirm) { //这里是点击了确定以后
                console.log('用户点击确定')
                wx.navigateTo({
                  url: "../index/index" //这里是上传成功后确定返回页面
                })
              } else { //这里是点击了取消以后
                console.log('用户点击取消')
                wx.navigateTo({
                  url: "../index/index" //这里是上传成功后取消返回页面
                })
              }
            }
          })
        }
      },
      fail(e) {
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        });
      },
      complete() {
        wx.hideToast(); //隐藏Toast
      }
    })
  }
})

 backend receiving

I am currently using the SSM framework and need to add configuration in springmvc.xml

 springmvc.xml

<!-- 配置文件上传相关 -->
    <!--配置文件解析器对象,有了它就可以进行文件上传-->
    <!-- 配置文件解析器-->
    <!-- 此处id为固定写法,不能随便取名-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576"></property>
    </bean>

 Controller layer code

//接收小程序上传的图片
    @RequestMapping(value = "/upload", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String[] uploadfile(MultipartFile[] file, HttpServletRequest request) {
        //本地服务器图片文件地址
        String dir = "D:\\images";
        String[] b = null;
        for (MultipartFile files : file) {
            String filename = files.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));
            String path = filename;
            //创建要保存文件的路径
            String time = new Date().getTime() + "." + suffix;
            String[] a = {path, time};
            File dirFile = new File(dir, time);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            try {
                //将文件写入创建的路径
                files.transferTo(dirFile);
                return a;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return b;
    }

 Remember the most important point: the name file of the applet and the name file received by the background Controller must be consistent in order to transfer the picture to the background

Guess you like

Origin blog.csdn.net/qq_55917018/article/details/130088551