微信小程序 图片上传到文件服务器

业务需求:

图片先上传到后台文件服务器,服务器返回图片的id及相关信息,再和其他要提交的内容一块提交到后台接口。

话不多说,上代码

index.wxml

html 复制代码
<van-uploader max-count="5" multiple file-list="{{ photoDtoList }}" bind:after-read="afterRead" bind:delete="deleteUploadFile" />

index.js

javascript 复制代码
import publicApi from '@/api/public';

data:{
    photoDtoList: []
},
// 上传照片
  async afterRead(e){
    const { file } = e.detail;
    let res = await publicApi.filesUpload(file);
    let arr = [];
    if(res.success){
      res.success.forEach((item,index)=>{
        // 具体根据自己的业务修改,url为图片预览的地址,想要上传完可以直接预览必须要加isImage:true
        arr.push({
          photoId:item.id,
          photoSeq: index+1,
          isImage: true,
          url: `${config.sfss_url}space/${item.id}/preview`
        })
      })
      let list = []
      list = [
        ...this.data.photoDtoList,
        ...arr
      ]
      this.setData({
        photoDtoList: list
      })
    }
  },
  // 删除图片
  deleteUploadFile(e){
    const { index } = e.detail;
    this.data.photoDtoList.forEach((item,i) =>{
      if(i === index){
        this.data.photoDtoList.splice(index,1)
      }
    })
    this.setData({
      photoDtoList: this.data.photoDtoList
    })
  },

多文件上传接口封装

javascript 复制代码
filesUpload(files) {
    let formData = new FormData();
    files.forEach(item=>{
      formData.appendFile('file', item.tempFilePath)
    })
    const data = formData.getData();
    return request({
      url: `${sfss_url}/space/files`,
      method: "POST",
      header: {
        'content-type': data.contentType
      },
      data: data.buffer
    })
  },
相关推荐
远山枫谷15 小时前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序
木易士心2 天前
一文读懂:微信小程序云数据库直连原理与使用指南
微信小程序·serverless
明月_清风2 天前
小程序云函数:从入门到全栈的“降维打击”指南
前端·微信小程序·小程序·云开发
拉不动的猪3 天前
移动端调试工具VConsole初始化时的加载阻塞问题
前端·javascript·微信小程序
茶杯梦轩3 天前
从零起步学习RabbitMQ || 第二章:RabbitMQ 深入理解概念 Producer、Consumer、Exchange、Queue 与企业实战案例
服务器·后端·消息队列
WangHappy5 天前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端5 天前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
YuMiao5 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
icebreaker6 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker6 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序