|
幾乎每個程序都需要用到圖片。 在小程序中我們可以通過image組件顯示圖片。 當(dāng)然小程序也是可以上傳圖片的,微信小程序文檔也寫的很清楚。 上傳圖片首先選擇圖片
通過wx.chooseImage(OBJECT)實現(xiàn) 
官方示例代碼 wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths
}
})
圖片最多可以選擇9張, 也可以通過拍攝照片實現(xiàn),當(dāng)選擇完圖片之后會獲取到圖片路徑, 這個路徑在本次啟動期間有效。 如果需要保存就需要用wx.saveFile(OBJECT) 上傳圖片
通過wx.uploadFile(OBJECT) 可以將本地資源文件上傳到服務(wù)器。 原理就是客戶端發(fā)起一個 HTTPS POST 請求,其中 content-type為 multipart/form-data。

官方示例代碼 wx.chooseImage({
success: function(res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://example.weixin.qq.com/upload',
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': 'test'
},
success: function(res){
var data = res.data
}
})
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
示例代碼看完了官方文檔, 寫一個上傳圖片就沒有那么麻煩了,下面是真實場景的代碼 import constant from '../../common/constant';
Page({
data: {
src: "../../image/photo.png",
},
onLoad: function (options) {
},
uploadPhoto() {
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths;
upload(that, tempFilePaths);
}
})
}
})
function upload(page, path) {
wx.showToast({
icon: "loading",
title: "正在上傳"
}),
wx.uploadFile({
url: constant.SERVER_URL + "/FileUploadServlet",
filePath: path[0],
name: 'file',
header: { "Content-Type": "multipart/form-data" },
formData: {
'session_token': wx.getStorageSync('session_token')
},
success: function (res) {
console.log(res);
if (res.statusCode != 200) {
wx.showModal({
title: '提示',
content: '上傳失敗',
showCancel: false
})
return;
}
var data = res.data
page.setData({
src: path[0]
})
},
fail: function (e) {
console.log(e);
wx.showModal({
title: '提示',
content: '上傳失敗',
showCancel: false
})
},
complete: function () {
wx.hideToast();
}
})
}
|