(小程序篇:二)服务器接收小程序图片

小程序图片上传,在服务器上接收小程序上传的图片

前面一篇介绍了本地搭建小程序测试服务器,但是有一定局限性:不能上传图片。因为小程序上传图片需要验证公用ssl证书,使用一些不正规的免费证书不能完成上传。所以我在阿里云上申请了一个用来测试,方法:linux服务器配置https 。当完成这些准备工作后,就可以开始文件上传功能的开发了。
小程序上传文件及其他网络访问接口和普通网络请求是相同的,如果在请求过程中数据传输失败或者有其他错误,处理方式和普通网络请求处理方式相同。
小程序由微信提供接口,开发需按照一定规范,没有那么灵活,以下是文件上传:

  chooseWxImage: function (type) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) { 
        that.setData({
          tempFilePaths: res.tempFilePaths,
        }), 
        that.uploadImage(res.tempFilePaths[0]) 
      }
    })
  },
  uploadImage: function (type) {
    wx.uploadFile({
      url: 'https://api.**域名**.com/upload',
      method: "POST",
      filePath: type,
      name: 'wximage',
      header: {
        'content-type': 'multipart/form-data'
      },
      data: {
      	// 直接使用file,接口会按上传文件处理。写成带引号形式“file”是错误的
        file: type.data
      },
      success: function (res) {
        //do something
      },
      fail: function (res) {
        //do something
      }
    })
  }

接收工程是使用的springboot框架,以下是服务器接收:

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(
            HttpServletRequest request,
            // 此处file和请求参数中的file对应,content-type按照 multipart/form-data格式,否则不对应
            @RequestParam("file") MultipartFile file) {
 		String str;
        File saveFile = new File(request.getSession().getServletContext().getRealPath("/upload/") + "test.jpg");
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }
        // 文件保存路径
        System.out.println(saveFile.getParentFile().toString());
        try {
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
            out.write(file.getBytes());
            out.flush();
            out.close();
            str = "上传成功";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            str = "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            str = "上传失败," + e.getMessage();
        } 
        return str;
    }

如果调试过程中需要查看请求头及请求体信息,直接使用getHeader()方法可能出现错误:*** has already been called for this request。解决方法可参考博客:https://blog.youkuaiyun.com/noseew/article/details/79179892

参考资料:
https://blog.youkuaiyun.com/xxkalychen/article/details/77842638
https://www.cnblogs.com/ityouknow/p/8298344.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值