選取相冊及本地預覽
- 選擇手機相冊
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]);
}
}
}
});
},
- 顯示照片列表
<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>
- 照片本地預覽
previewImg(item) {
wx.previewImage({
urls: this.tempFilePaths,
current: item
});
}
使用七牛雲圖片上傳
七牛雲提供了微信小程序sdk版本
-
下載七牛雲微信小程序sdk
https://developer.qiniu.com/sdk#community-sdk -
下載之后我們將qiniuUploader.js文件放置在static/lib目錄下
-
在vue文件中引入
import qiniuUploader from "../../../../../static/lib/qiniuUploader";
- 上傳圖片到七牛雲
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;
}
);
}
},
