微信小程序上传图片到七牛

要在小程序做一个类似发布朋友圈的效果,图文结合。设计图效果如下:

在这里我用的是小程序form组件,上面文字用textrea,下面传图片的时候,我们后端用到了七牛云,得先把图片上传到七牛云上面,然后拿到返回地址,再以数组的形式传给后端。

代码如下:首先wxml:

<view class="container">
<form bindsubmit="uploadIssued">
    <view class="shareContent">
        <textarea class="" value="{{value}}"bindblur="bindTextrea"  name="describe" placeholder="专业精装批墙,乳胶漆,批墙。但受委屈哦空额看......">

        </textarea>
    </view>
    <view class="uploadImg">
        <view class="uploadPic1" wx:for="{{imgs}}">
           <image class='imgList' wx:for-item="item" src='{{item}}' data-index="{{index}}" wx:key="*this" bindtap="previewImg" />
           <icon class='imgCancel' type="clear" size='25' data-index="{{index}}" color="red" catchtap="deleteImg"></icon>
        </view>
        <view class="uploadPic1 addPic">
            <image class="addImg"  bindtap="addImg" wx:if="{{isShowAdd}}" src="../../images/uploadImg.png"></image> 
        </view>
    </view>
    <x-button button-x="buttonClass">
		<button  form-type="submit">
			上传发布
		</button>
	</x-button>
</form>
</view>

然后wxss:

.container{
    width: 100%;
    padding: 40rpx;
    box-sizing: border-box;
}
.shareContent{
    width:670rpx;
    height:434rpx;
    background:rgba(255,255,255,1);
    box-shadow:0rpx 8rpx 20rpx 10rpx rgba(233,236,249,1);
    border-radius:24rpx;
    box-sizing: border-box;
    padding: 32rpx 34rpx;
}
.shareContent textarea{
    width: 100%;
    height: 100%;
    font-size: 28rpx;
    color: #333;
}
.uploadImg{
    width: 100%;
    height: 152rpx;
    margin-top: 30rpx;
    display: flex;
    flex-direction: row;
}
.uploadPic1{
    width: 152rpx;
    height: 152rpx;
    border-radius: 24rpx;
    margin-right: 30rpx;
    position: relative;
}
.uploadPic1 image{
    width: 152rpx;
    height: 152rpx;
    border-radius: 24rpx;
}
.uploadImg .addPic{
    background: #F6F6E9;
    padding: 34rpx 32rpx 32rpx 34rpx;
    box-sizing: border-box;
}
.addPic .addImg{
    width: 86rpx;
    height: 86rpx;
}
.buttonClass{

    margin-top: 360rpx;
    height: 78rpx;
    box-sizing: border-box;
    overflow: hidden;
}
.buttonClass button{
    background-color: #F2855E;
    height: 78rpx;
    color: #fff;
}
.uploadPic1 .imgCancel{
    position: absolute;
    right: 0;
    top: 0;
    z-index: 100;
}

再然后javascript:

// pages/shareCraft/shareCraft.js
import request from "../../service/network";
const qiniuUploader = require("../../utils/qiniuUploader");
const app = getApp();
let adds={}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        describe:"",
        imgs:[],
        countNum: 3, //设定一次性选择图片的上限值
        max: 3 ,//设定上传图片总数的上限值,与countNum相同
        imgArr:[],
        picPaths:[],//网络路径
        isShowAdd:true,
        value:"",
        uptoken:"",
        imageURL:""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //调用拿到token
      this.fetchUptoken();
    },
    //通过url地址获取到七牛的token
    fetchUptoken(e){
      wx.request({		//拿到token
        url: 'https://dubbing.csweimei.cn/upload/YuanLiToken',
        header: {
          'Content-Type': 'application/json;charset=UTF-8'
        },
        method: 'POST',
        success: (res) => {
          console.log(res);
          let uptoken = res.data.token;
          console.log(uptoken);
          this.setData({
            uptoken
          })
        }
      })
    },

     //添加图片
  addImg: function (e) {
    //var that = this;
    wx.chooseImage({
      count: this.data.countNum, // 上传图片上限值
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: res => {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = this.data.imgs;
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length >= this.data.max) {
            this.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
            //上传图片达到上限count值时,隐藏添加按钮
            if (imgs.length >= this.data.max) {
              this.setData({
                isShowAdd: false
              });
            }
          }
        }
        this.setData({
          imgs: imgs,
          countNum: this.data.max - imgs.length //每增加一张图片,动态计算还可添加照片的数量
        })
        console.log(imgs);
        
        this.pictureUploadqiniuMethod(imgs);
      }
    })
  
  },
//上传图片到七牛的函数
  pictureUploadqiniuMethod(imgs){
    console.log(imgs.length);
    for(let i=0;i<imgs.length;i++){
      let filePath = imgs[i];
      var imgName = filePath.substr(30,50);
      
      let uptoken = this.data.uptoken;
      console.log(uptoken);
      qiniuUploader.upload(filePath,(res)=>{
        console.log(res);
        let imageURL = res.imageURL;
        let imgArr=[];
        imgArr.push({'imgurl':imageURL});
        this.setData({
          imgArr
        })
      },
      (error)=>{
        console.log("error"+error);
      },
      {
        uptoken:this.data.uptoken,
        uptoken_url:"https://dubbing.csweimei.cn/upload/YuanLiToken",
        region:'SCN',
      }
      )
    }
  },
  //预览图片
  previewImg(e){
    let index = e.currentTarget.dataset.index;
    let imgs = this.data.imgs;
    wx.previewImage({
      current:imgs[index],
      urls:imgs
    })
  },
  //删除图片
  deleteImg(e){
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs,
      countNum: this.data.max - imgs.length
    })
    if (imgs.length < this.data.max) {
      this.setData({
        isShowAdd: true
      })
    }
  },
  //请求接口上传发布
  uploadIssued(e){
    console.log("11");
    let userid = wx.getStorageSync('userPhone');
    let name = wx.getStorageSync('nickname');
    let headImg = wx.getStorageSync('avatarUrl');
    let describe = e.detail.value.describe;
    console.log(describe);
    //上传
    let imgs = this.data.imgArr;
    console.log(imgs);
    request({
      url:"/MasterCircle/ReleaseCircle",
      method:"post",
      data:{
        userid,
        name,
        headImg,
        describe,
        imgs
      }
    }).then(res=>{
      console.log(res);
      if(res.data.code==0){
        wx.showToast({
          title: '操作成功',
        })
      }else if(res.data.code==-1){
        wx.showToast({
          title: '操作失败',
          icon:"none",
          duration:2000
        })
      }
    })
    
  },
   
})

备注:上传图片到七牛主要 uptoken,uptoken_url 和 region 这三个元素,

region中的 ECN, SCN, NCN, NA,分别对应七牛的:华东,华南,华北,北美四个区域。

自己相对应填写好就行了。我也是第一次做这个,上传图片到七牛云,查了好半天资料才做成的,不足之处还望指教!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值