微信小程序之上传图片(含前后端代码例子)

此代码示例,能够让你成功将图片上传至后端,后端做相应的处理,然后返回成功码。

前端小程序代码

index.wxml:

<view class='content'>
  <view class='img-box'>
    <view class='img-list'>
      <block wx:for="{{detailPics}}" wx:key="index">
        <view class='img-item'>
          <image src='{{item}}' bindlongpress="bindlongpressimg" data-id='{{index}}'></image>
        </view>
      </block>
      <view class='chooseimg' bindtap='uploadDetailImage'>
        <view class="weui-uploader__input-box"></view>
      </view>
    </view>
    <view class='tips'>长按对应的图片即可删除</view>
  </view>
</view>

index.wxss:

.content {
  width: 100%;
  background-color: #fff;
}

.img-list {
  display: flex;
  display: -webkit-flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.img-item {
  width: 30%;
  text-align: left;
  margin-right: 20rpx;
  margin-bottom: 10rpx;
}

.img-item image {
  width: 180rpx;
  height: 180rpx;
}

.submit-btn {
  width: 100%;
  background-color: #fff;
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  font-size: 30rpx;
  position: fixed;
  bottom: 100rpx;
}

.chooseimg {
  background-color: #fff;
}

.weui-uploader__input-box {
  float: left;
  position: relative;
  margin-right: 9px;
  margin-bottom: 9px;
  width: 180rpx;
  height: 180rpx;
  border: 1px solid #d9d9d9;
}

.weui-uploader__input-box:before {
  width: 2px;
  height: 39.5px;
}

.weui-uploader__input-box:after, .weui-uploader__input-box:before {
  content: " ";
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background-color: #d9d9d9;
}

.weui-uploader__input-box:after {
  width: 39.5px;
  height: 2px;
}

.weui-uploader__input-box:after, .weui-uploader__input-box:before {
  content: " ";
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  background-color: #d9d9d9;
}

.tips {
  color: #666;
  font-size: 24rpx;
  padding-bottom: 20rpx;
}

.img-box {
  width: 92%;
  margin: auto;
  padding-top: 20rpx;
}

index.js:

// component/uploadImages/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    count: { //最多选择图片的张数,默认9张
      type: Number,
      value: 9
    },
    uploadUrl: { //图片上传的服务器路径
      type: String,
      value: ''
    },
    showUrl: { //图片的拼接路径
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    detailPics: [], //上传的结果图片集合
  },

  ready: function () {
    console.log(this.data)
  },

  /**
   * 组件的方法列表
   */
  methods: {

    uploadDetailImage: function (e) { //这里是选取图片的方法
      var that = this;
      var pics = [];
      var detailPics = that.data.detailPics;
      if (detailPics.length >= that.data.count) {
        wx.showToast({
          title: '最多选择' + that.data.count + '张!',
        })
        return;
      }
      wx.chooseImage({
        count: that.data.count, // 最多可以选择的图片张数,默认9
        sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
        sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
        success: function (res) {
          var imgs = res.tempFilePaths;
          for (var i = 0; i < imgs.length; i++) {
            pics.push(imgs[i])
          }
          that.uploadimg({
            url: "http://www.test.com//test-api/wechat/applet/api/uploadUserAvatar", //这里是你图片上传的接口
            path: pics, //这里是选取的图片的地址数组
          });
        },
      })

    },
    //多张图片上传
    uploadimg: function (data) {
      wx.showLoading({
        title: '上传中...',
        mask: true,
      })
      var that = this,
        i = data.i ? data.i : 0,
        success = data.success ? data.success : 0,
        fail = data.fail ? data.fail : 0;
      wx.uploadFile({
        url: data.url,
        filePath: data.path[i],
        name: 'file',
        formData: {"userId":"35"},
        success: (resp) => {
          wx.hideLoading();
          success++;
          var str = resp.data //返回的结果,可能不同项目结果不一样

          console.log(str);
          // var pic = JSON.parse(str);
          // var pic_name = that.data.showUrl + pic.Data;
          // var detailPics = that.data.detailPics;
          // detailPics.push(pic_name)
          // that.setData({
          //   detailPics: detailPics
          // })
        },
        fail: (res) => {
          fail++;
          console.log('fail:' + i + "fail:" + fail);
        },
        complete: () => {
          i++;
          if (i == data.path.length) { //当图片传完时,停止调用     
            console.log('执行完毕');
            console.log('成功:' + success + " 失败:" + fail);
            var myEventDetail = {
              picsList: that.data.detailPics
            } // detail对象,提供给事件监听函数
            var myEventOption = {} // 触发事件的选项
            that.triggerEvent('myevent', myEventDetail, myEventOption)//结果返回调用的页面
          } else { //若图片还没有传完,则继续调用函数
            data.i = i;
            data.success = success;
            data.fail = fail;
            that.uploadimg(data);//递归,回调自己
          }
        }
      });
    },

  }
})

后端Java代码(这里我使用的是第三方存储,如腾讯云,如果读者朋友们是使用第三方存储替换是一件很容易的事情)

核心代码如下:

@PostMapping("/uploadUserAvatar")
@ApiOperation(value = "上传用户头像", notes = "上传用户头像")
public JSONObject uploadUserAvatar(HttpServletRequest request) {

    JSONObject json = new JSONObject();
    try {

        String userId = request.getParameter("userId");

        COSClientUtil cosClientUtil = new COSClientUtil();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        // 获取上传的文件
        MultipartFile multiFile = multipartRequest.getFile("file");

        
        
        String name = cosClientUtil.uploadFileCos(multiFile);

        // 获取文件路径
        String fileUrl = cosClientUtil.getFileUrl(name);
        
        Console.log("fileUrl:"+fileUrl);
        
        
        // 对文件路径进行处理
        String dbFileUrl = fileUrl.substring(0, fileUrl.indexOf("?"));
        
        
        Console.log("dbFileUrl:"+dbFileUrl);

        User user = new User();
        user.setId(Integer.parseInt(userId));
        user.setSmallAvatar(dbFileUrl);

        boolean isUploadUserAvatar = userService.updateById(user);

        if (isUploadUserAvatar) {
            json.put(ResponseUtils.CODE, ResponseUtils.SUCCESS_CODE);
            json.put(ResponseUtils.MSG, ResponseUtils.SUCCEESS_MSG);
        } else {
            json.put(ResponseUtils.CODE, ResponseUtils.ERROR_CODE);
            json.put(ResponseUtils.MSG, ResponseUtils.ERROR_MSG);
        }

    } catch (Exception e) {
        e.printStackTrace();

        json.put(ResponseUtils.CODE, ResponseUtils.ERROR_CODE);
        json.put(ResponseUtils.MSG, ResponseUtils.ERROR_MSG);

    }

    return json;
}

 

posted @ 2019-09-15 20:15  挑战者V  阅读(21060)  评论(1编辑  收藏  举报