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

前端之家收集整理的这篇文章主要介绍了微信小程序之上传图片(含前后端代码例子)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

前端小程序代码

index.wxml:

<view class='content'>
  <view img-Box'>
    <view img-list'>
      <block wx:for="{{detailPics}}" wx:key=index">
        <view img-item'>
          <image src={{item}}' bindlongpress=bindlongpressimg" data-id={{index}}'></image>
        </view>
      </block>
      <view chooseimg' bindtap=uploadDetailImage'>
        <view weui-uploader__input-Box"></view>
      </view>
    </view>
    <view 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: 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: ;
  -webkit-transform: translate(-50%,-);
  transform: translate(-);
  background-color: #d9d9d9;
}

.weui-uploader__input-Box:after {
  width: .5px;
  height: 2px;
}

.weui-uploader__input-Box:after,1)">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,1)">''图片的拼接路径

    }
  },*
   * 组件的初始数据
   
  data: {
    detailPics: [],1)">上传的结果图片集合
  },ready: function () {
    console.log(this.data)
  },1)">*
   * 组件的方法列表
   
  methods: {

    uploadDetailImage: function (e) { 这里是选取图片方法
      var that = ;
      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,1)"> 最多可以选择的图片张数,默认9
        sizeType: [original',compressed'], original 原图,compressed 压缩图,默认二者都有
        sourceType: [albumcamera 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",1)">这里是你图片上传的接口
            path: pics,1)">这里是选取的图片的地址数组
          });
        },})

    },1)">多张图片上传
    uploadimg: function (data) {
      wx.showLoading({
        title: 上传中...true= data.i ? data.i : 0= data.fail ? data.fail : ;
      wx.uploadFile({
        url: data.url,filePath: data.path[i],name: fileuserId":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);
        },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结果返回调用页面
          } else { 图片还没有传完,则继续调用函数
            data.i = i;
            data.success = success;
            data.fail = fail;
            that.uploadimg(data);递归,回调自己
          }
        }
      });
    },}
})

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

核心代码如下:

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

    JSONObject json = new JSONObject();
    try {

        String userId = request.getParameter();

        COSClientUtil cosClientUtil =  COSClientUtil();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

         获取上传文件
        MultipartFile multiFile = multipartRequest.getFile();

        
        
        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 =  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);

    }

     json;
}

 

猜你在找的微信小程序相关文章