小程序文件上傳原生寫法


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、效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM