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

业务需求:

图片先上传到后台文件服务器,服务器返回图片的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
    })
  },
相关推荐
捷米研发三部4 分钟前
EtherNet/IP转CAN协议转换网关实现罗克韦尔 PLC与压力传感器通讯在轮胎压力监测系统的应用案例
服务器·网络
白玉瑕14 分钟前
服务器的构成
运维·服务器
内存不泄露15 分钟前
酒店预订管理平台及小程序
小程序
2501_9159184125 分钟前
除了 Perfdog,如何在 Windows 环境中完成 iOS App 的性能测试工作
android·ios·小程序·https·uni-app·iphone·webview
石像鬼₧魂石30 分钟前
80 端口(Web 服务)渗透测试完整总结(含踩坑 + 绕过 + 实战流程)
linux·运维·服务器·前端·网络·阿里云
米高梅狮子37 分钟前
11. Linux 防火墙管理
linux·运维·服务器
HABuo1 小时前
【Linux进程(五)】进程地址空间深入剖析-->虚拟地址、物理地址、逻辑地址的区分
linux·运维·服务器·c语言·c++·后端·centos
开开心心_Every1 小时前
安卓做菜APP:家常菜谱详细步骤无广简洁
服务器·前端·python·学习·edge·django·powerpoint
五仁火烧1 小时前
HTTP 服务器
服务器·网络·网络协议·http
weixin_lynhgworld1 小时前
[特殊字符]短剧小程序开发:开启娱乐新纪元的钥匙[特殊字符]
小程序