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

业务需求:

图片先上传到后台文件服务器,服务器返回图片的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
    })
  },
相关推荐
知已难寻3 小时前
03 · OpenStack的计算管理 Nova
运维·服务器·开发语言·云原生·云计算·openstack·开源软件
huainingning4 小时前
Windows syslog日志服务器搭建与模拟器对接
运维·服务器·智能路由器
say_fall4 小时前
【Linux系统编程】Ext 文件系统:磁盘与存储、文件与目录、现代计算机究竟如何寻找文件
linux·运维·服务器·数据库·c++
wacsii4 小时前
【Linux进程(一)】Linux 进程初探:操作系统如何管理进程?fork() 为什么返回两次?
linux·运维·服务器
共享家95275 小时前
408 操作系统第一章
服务器·数据库·windows
云飞云共享云桌面5 小时前
1台SolidWorks服务器如何承载10个设计并发?
运维·服务器·网络·3d·制造
墨理学AI7 小时前
虚拟机导致的服务器交换内容占用过大(服务器卡顿)问题 快速解决
运维·服务器
程序猿老A8 小时前
轻量应用服务器怎么搭建个人网站?
服务器
盛世宏博智慧档案8 小时前
一站式智慧档案解决方案,如何实现防火防盗漏水多维度安全监测实践
服务器·网络·数据库
熊猫钓鱼>_>9 小时前
平行视界兼容模式与魔法变量配置避坑【鸿蒙心迹】
运维·服务器·开发语言·笔记·华为·harmonyos·openharmony