您的位置:首页 > 移动开发 > 微信开发

小程序开发笔记(六)--使用七牛云上传图片

2019-05-27 00:43 1486 查看

选取相册及本地预览

  1. 选择手机相册
preUpload() {
let that = this;
// let imglist=[];
wx.chooseImage({
count: 9, //最多可以选择的图片张数
sizeType: ["original", "compressed"],
sourceType: ["album", "camera"],
success(res) {
console.log("res", res);
// tempFilePath可以作为img标签的src属性显示图片
// that.tempFilePaths = res.tempFilePaths;
for (let i = 0; i < res.tempFilePaths.length; i++) {
if (that.tempFilePaths.length < 9) {
that.tempFilePaths.push(res.tempFilePaths[i]);
}
}
}
});
},
  1. 显示照片列表
<ul class="photos">
<li class="photo" v-for="(item,index) in tempFilePaths" :key="index">
<img class="photo-pic" :src="item" alt @click="previewImg(item)">
<img class="photo-delete" src="/static/icon/icon_delete.png" @click="deletePhoto(index)">
</li>
<li class="photo upload-btn" @click="preUpload" v-if="tempFilePaths.length<9">上传</li>
</ul>
  1. 照片本地预览
previewImg(item) {
wx.previewImage({
urls: this.tempFilePaths,
current: item
});
}

使用七牛云图片上传

七牛云提供了微信小程序sdk版本

  1. 下载七牛云微信小程序sdk
    https://developer.qiniu.com/sdk#community-sdk

  2. 下载之后我们将qiniuUploader.js文件放置在static/lib目录下
  3. 在vue文件中引入
import qiniuUploader from "../../../../../static/lib/qiniuUploader";
  1. 上传图片到七牛云
doPreAdd() {
if(this.tempFilePaths.length<=0){
this.doSave();
return;
}
// 先上传图片 -》发布动态并保存图片地址
let that = this;
// let imgList = [];
let count = 0; //count记录当前已经上传到第几张图片
// 上传多张
for (let i = 0; i < this.tempFilePaths.length; i++) {
qiniuUploader.upload(
this.tempFilePaths[i],
res => {
count++;
that.imgList.push(res.imageURL);
if (count == that.tempFilePaths.length) {
//全部上传完成  调用保存接口
that.doSave();
}
},
error => {
console.error("error: " + JSON.stringify(error));
that.log = "error: " + JSON.stringify(error);
},
{
key:`www/${new Date().getFullYear()}/${new Date().getMonth()+1}/${new Date().getDate()}/${new Date().getTime()}.jpg`,//设置文件名
region: "ECN", // NCN华北区    ECN华东区
uptokenURL: api.getQiniuToken(),
domain: "http://xxx.xxx.cn",
shouldUseQiniuFileName: false
// key: 'testKeyNameLSAKDKASJDHKAS'
// uptokenURL: 'myServer.com/api/uptoken'
},
// null, // 可以使用上述参数,或者使用 null 作为参数占位符
progress => {
console.log("上传进度", progress.progress);
console.log("已经上传的数据长度", progress.totalBytesSent);
console.log(
"预期需要上传的数据总长度",
progress.totalBytesExpectedToSend
);
that.log = "上传进度" + progress.progress;
},
cancelTask => {
// that.setData({ cancelTask });
this.cancelTask = cancelTask;
}
);
}
},
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐