小程序文件上传原生写法

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

 

posted @   Pavetr  阅读(903)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示