小程式上傳圖片筆記
阿新 • • 發佈:2018-12-21
小程式上傳單個圖片時,選擇圖片後即時上傳到伺服器,伺服器返回圖片路徑並儲存至data中,最後提交頁面資料時一併將頁面資料及返回路徑提交
wxml:
<view class='item-ot'>
<view class='itemTxt2'></view>
<view class="item">
<!-- 新增按鈕 -->
<view class="addIcon" bindtap="chooseImage2" wx:if="{{imgBoolean2}}">
<view class =''>+</view>
</view>
<!-- 上傳的圖 -->
<view class='itemImg' >
<image src="{{legal_opposite_img}}" data-src="{{legal_opposite_img}}" bindtap="previewImage2" mode="aspectFill" />
<!-- 刪除按鈕 -->
<view class="delete" bindtap="deleteImg2" data-index ="{{index2}}">X</view>
</view>
</view>
</view>
js:
data: {
uploadedImages: [],
uploadedImages2: [],
uploadedImages3: [],
uploadedImages4: [],
imgBoolean: true,
imgBoolean2: true,
imgBoolean3: true,
imgBoolean4: true,
legal_face_img: '' ,
legal_opposite_img: '',
business_img: '',
legal_hand_img: '',
up_legal_face_img: '',
up_legal_opposite_img: '',
up_business_img: '',
up_legal_hand_img: ''
},
chooseImage2: function (e) {
var that = this;
// 選擇圖片
wx.chooseImage({
count: 1, // 預設9,為1選擇一張圖片
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
success: function (res) {
// 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
var tempFilePaths = res.tempFilePaths;
that.upload('up_legal_opposite_img', tempFilePaths);
that.setData({
legal_opposite_img: tempFilePaths[0],
imgBoolean: false
});
}
})
},
// 圖片預覽
previewImage: function (e) {
var current = e.target.dataset.src
wx.previewImage({
current: current,
urls: [current]
})
console.log("這是1" + current);
},
//刪除圖片
deleteImg: function (e) {
var that = this;
var images = that.data.uploadedImages;
that.setData({
uploadedImages: images,
imgBoolean: true
});
},
/**
* 上傳圖片
*/
upload(imgPath, path) {
let that = this;
wx.showToast({
icon: "loading",
title: "正在上傳"
}),
wx.uploadFile({
url: "",
filePath: path[0], // 上傳一張圖片
name: 'file',
header: {
'Content-Type': 'application/json',
},
formData: {
file: path[0] // 上傳一張圖片
},
success: function (res) {
console.log(res);
if (res.statusCode != 200) {
wx.showModal({
title: '提示',
content: '上傳失敗',
showCancel: false
})
return;
} else {
that.setData({
[imgPath]: JSON.parse(res.data).data[0] //將返回的圖片路徑儲存至data中,以供同其他資料一同提交
})
}
},
fail: function (e) {
console.log(e);
wx.showModal({
title: '提示',
content: '上傳失敗',
showCancel: false
})
},
complete: function () {
wx.hideToast(); //隱藏Toast
}
})
},