微信小程式 —— 上傳檔案到伺服器(例:上傳圖片到伺服器)
阿新 • • 發佈:2019-01-03
上傳圖片到伺服器:
1.先在前端寫一個選擇圖片的區域來觸發wx.chooseImage介面並用wx.setStorage介面把圖片路徑存起來。
-wxml
<view class="shangchuan" bindtap="choose">
<image style="width:100%;height:100%;" src="{{tempFilePaths}}"></image>
</view>
<button formType='submit' class="fabu">釋出專案</button>
/**選擇圖片 */
choose: function () {
var that = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
success: function (res) {
var tempFilePaths = res.tempFilePaths
that.setData({
tempFilePaths: res.tempFilePaths
})
console.log(res.tempFilePaths)
wx.setStorage({ key: "card" , data: tempFilePaths[0] })
}
})
},
2.使用wx.uploadFile將剛才上傳的圖片上傳到伺服器上
formSubmit2: function (e) {
var that = this
var card = wx.getStorageSync('card')
wx.uploadFile({
url: app.globalData.create_funds,
filePath: card,
name: 'card',
formData: {
'user_id' : app.globalData.user_id,
'person': e.detail.value.person,
'company': e.detail.value.company,
},
success: function (res) {
console.log(res)
}
})
}
}
},