這篇文章主要介紹了微信小程序中如何實現拍照或從相冊選取圖片上傳,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
upload.wxml
<!--pages/upload/upload.wxml--> <button bindtap='uploadPhoto'>拍照選取照片上傳</button>
upload.js
// pages/upload/upload.js
Page({
data: {
imgData: []
},
uploadPhoto(e) { // 拍攝或從相冊選取上傳
let that = this;
wx.chooseImage({
count: 1, // 默認9
sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
success(res) {
let tempFilePaths = res.tempFilePaths; // 返回選定照片的本地路徑列表
that.upload(that, tempFilePaths);
}
})
},
upload(page, path) { // 上傳圖片
wx.showToast({ icon: "loading", title: "正在上傳……" });
wx.uploadFile({
url: '上傳圖片接口url', //后端接口
filePath: path[0],
name: 'file',
header: {
"Content-Type": "multipart/form-data"
},
success(res) {
if (res.statusCode != 200) {
wx.showModal({ title: '提示', content: '上傳失敗', showCancel: false });
return;
} else{
console.log("上傳成功! 可對返回的值進行操作,比如:存入imgData;");
}
},
fail(e) {
wx.showModal({ title: '提示', content: '上傳失敗', showCancel: false });
},
complete() {
wx.hideToast(); //隱藏Toast
}
})
}
})ps:以上是單圖上傳,如果需要多圖上傳,請看下方:
// pages/publish/publish.js
Page({
data: {
imgData: []
},
uploadPhoto(e) { // 拍攝或從相冊選取上傳
let that = this;
wx.chooseImage({
count: 9 - that.data.imgData.length, // 默認最多上傳9張
sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
success(res) {
let tempFilePaths = res.tempFilePaths; // 返回選定照片的本地路徑列表
that.upload(that, tempFilePaths);
}
})
},
upload(page, path) { // 上傳圖片
let that = this;
wx.showToast({ icon: "loading", title: "正在上傳……" });
for (var i=0; i<path.length; i++) {
wx.uploadFile({
url: '上傳圖片接口url', //后端接口
filePath: path[i],
name: 'file',
header: app.globalData.header,
success(res) {
if (res.statusCode != 200) {
wx.showModal({
title: '提示',
content: '第' + i +'張圖片上傳失敗',
showCancel: false
});
return;
} else {
console.log('第' + i +'張圖片上傳成功!可在此操作,比如:存入imgData;');
}
},
fail(e) {
wx.showModal({
title: '提示',
content: '第' + i +'張圖片上傳失敗',
showCancel: false
});
},
complete() {
wx.hideToast(); //隱藏Toast
}
})
}
}
})感謝你能夠認真閱讀完這篇文章,希望小編分享的“微信小程序中如何實現拍照或從相冊選取圖片上傳”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。