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

业务需求:

图片先上传到后台文件服务器,服务器返回图片的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
    })
  },
相关推荐
我是谁??2 小时前
Ubuntu22.04更换清华源
linux·运维·服务器
圣殿骑士-Khtangc3 小时前
Go字符串高效拼接性能对比与底层原理分析
服务器·前端·golang
不吃辣4904 小时前
vibe coding | 如何做一个AI制图小程序?
人工智能·小程序·ai编程
这个DBA有点耶4 小时前
数据库一体机架构演进:从硬件堆叠到软硬深度耦合
服务器·网络·数据库·硬件架构·运维开发·database·数据库架构
laboratory agent开发4 小时前
2026小程序服务商推荐:全域私域数字化工具选型深度解析
小程序
测试运维日常笔记4 小时前
Linux系统安装配置TigerVNC服务器完整指南
linux·运维·服务器
像风一样自由20205 小时前
加强版VScode结合remote-ssh远程连接服务器开发指南
服务器·vscode·ssh
雾时之林5 小时前
Linux----cron定时服务
linux·运维·服务器
wengqidaifeng7 小时前
1.从“会敲命令”到理解 Linux:15 个基础指令、文件树与命令执行的本质
linux·运维·服务器·ubuntu
tedcloud1237 小时前
book-to-skill 怎么部署?把技术书和文档转换成可复用的 AI Skill
运维·服务器·人工智能·开源·ai编程