小程式檔案上傳原生寫法
阿新 • • 發佈:2022-03-25
1、思路:就是把檔案上傳伺服器並獲得返回的儲存地址的連結儲存,比較簡單,直接上程式碼了,主要就是wx.chooseImage和wx.uploadFile,官網上也有https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
2、
html
<view class='add_item' wx:if="{{parent}}"> <view>圖示圖片</view> <view class="img_box"> <view wx:if="{{!form.iconUrl}}" class="choice" bindtap="choice" data-type="form.iconUrl"></view> <image wx:else bindtap="choice" class="imgUrl" src="{{form.iconUrl}}"></image> </view> </view> <view class='add_item' wx:if="{{parent}}"><view>分類圖片</view> <view class="img_box"> <view wx:if="{{!form.imgUrl}}" class="choice" bindtap="choice" data-type="form.imgUrl"></view> <image wx:else bindtap="choice" class="imgUrl" src="{{form.imgUrl}}"></image> </view> </view>
js
choice(e) { const type = e.currentTarget.dataset.type, _this = this wx.chooseMessageFile({ count: 1, // type: 'image', success(res) { app.globalData.uploads(res.tempFiles[0].path, `/file/api/upload?displayName=${res.tempFiles[0].name}&busiType=rollbackImg`).then(url => { _this.setData({ [type]: url.fileUrl }) }) } }) },
app.js
uploads(src, url, formData) { console.log(src, url, formData) wx.showLoading({ title: '上傳中', }) let header = { 'Content-Type': 'application/json', 'access-token': wx.getStorageSync('accessToken'), 'shop': shop } const base = this.base return new Promise((resolve, reject) => { wx.uploadFile({ filePath: src, name: 'file', url: `${base}${url}`, header, formData, success: (res) => { console.log(res) if (res.statusCode == 200) { res.data = JSON.parse(res.data) resolve(res.data) } else { wx.showToast({ title: res.data.msg || '請求失敗!', icon: "none", duration: 1500, }) reject(res) } wx.hideLoading() }, fail: (err) => { wx.hideLoading() reject(err) } }) }) }
3、效果