微信小程序端实现图片上传功能(后台java)

最近刚做完一个小程序商城,遇到很多坑,但是后来通过微信公众平台and百度顺利解决。下面跟大家分享一个小程序上传图片的功能。分三步走。

 

第一步,选择图片:wx.chooseImage()

第二步,上传图片:wx.uploadFile()

第三步,显示图片。

 

下面直接上代码(wxml代码我这边就不展示了)

 uploadPic: function (event) { //上传图片触发方法
    var that = this;
    wx.chooseImage({
      count: 9,  //最多可以选择的图片总数  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有  
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片  
        var tempFilePaths = res.tempFilePaths;
        console.log("-----------" + tempFilePaths);
        //启动上传等待中...  
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 10000
        })
        var uploadImgCount = 0;

        var uploadType = 3;

        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          wx.uploadFile({
            url: api.batchUploadFile, //后台文件上传接口
            filePath: tempFilePaths[i], //临时文件地址
            name: 'uploadfile_ant',
            formData: {
              'imgIndex': i
            },
            header: {
              "Content-Type": "multipart/form-data",
              "uploadType": uploadType,
              "token": wx.getStorageSync('token')
            },
            success: function (res) {
              if (res.statusCode == 200) { //成功
                var result = JSON.parse(res.data);
                console.log(result);
                if (result.code == 0) {
                  that.data.files.push(result.items[0]);
                } else {
                  wx.hideToast();
                  wx.showModal({
                    title: '错误提示',
                    content: result.msg,
                    showCancel: false,
                    success: function (res) { }
                  })
                }
              } else {
                console.info(res);
                wx.hideToast();
                wx.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false,
                  success: function (res) { }
                })
              }

              uploadImgCount++;

              //如果是最后一张,则隐藏等待中  
              if (uploadImgCount == tempFilePaths.length) {
                that.setData({
                  files: that.data.files
                });

                wx.hideToast();
              }
            },
            fail: function (res) {
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
                success: function (res) { }
              })
            }
          });
        }
      }
    });
  },

 

对于wx.chooseImage()这个是调用微信的原生的选择图片的方法,移动端的话可以是选择相册的照片或者直接拍的照片,一些属性的取值代码中的注释写的很清楚,我就不多bb。wx.uploadFile()其实就是调用后台文件上传接口把图片文件上传到自己的服务器(开发或者测试环境服务器),url是自己写好的文件上传接口,其他是一些参数。Content-Type一定要是文件类型("multipart/form-data"),下面附上java文件上传系统(我这边的需求是图片上传到服务器后要立刻显示出上传的图片,因此后台的文件上传接口把文件上传到服务器后还要把文件路径返回来)。

public AjaxResult batch() {
		AjaxResult result = new AjaxResult();
		try {
			Long merchantId = getMerchantIdByToken();
			int uploadType = Integer.parseInt(ServletUtils.getHeaderByName("uploadType"));

			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			List<FileItem> items = upload.parseRequest(ServletUtils.getRequest());
			logger.info("本次上传的文件数量:{}", items.size());

			List<String> resultFileUrls = new ArrayList<String>();
			for (FileItem item : items) {
				String name = item.getFieldName();
				logger.info("fieldName:{}", name);

				String folder = UploadTypeEnum.getByTargetType(uploadType).getFolder();

				// 判断是否是一个一般的表单域, 
				if (!item.isFormField()) {
					InputStream is = item.getInputStream();

					//创建文件目录
					String path = profile + merchantId + File.separatorChar + folder + File.separatorChar + item.getName();
					File file = new File(path);
					File fileParent = file.getParentFile();
					if (!fileParent.exists()) {
						fileParent.mkdirs();
					}
					file.createNewFile();

					FileOutputStream fos = new FileOutputStream(path);
					byte[] buff = new byte[1024];
					int len = 0;
					while ((len = is.read(buff)) > 0) {
						fos.write(buff);
					}
					is.close();
					fos.close();

					resultFileUrls.add("http://" + fileServerDomain + "/" + merchantId + "/" + folder + "/" + item.getName());
				}
			}
			result = AjaxResult.success("上传文件成功").putListData(resultFileUrls);
		} catch (Exception e) {
			result = AjaxResult.error("上传文件异常");
			e.printStackTrace();
		}
		return result;
	}

 

后台文件上传接口可以自己定义封装文件路径,比较灵活,不需要生搬硬套。我这边建议是按照一定的规则、归类存取,这样对于比较多文件的情况下方便查找。那么接下来你亲自操作一遍试试?有问题我们再探讨。

 

后续会不定时分享关于小程序的一些坑以及实现过程,期待的点个赞噢!

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值