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

业务需求:

图片先上传到后台文件服务器,服务器返回图片的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
    })
  },
相关推荐
C++忠实粉丝25 分钟前
Linux环境基础开发工具使用(2)
linux·运维·服务器
康熙38bdc1 小时前
Linux 环境变量
linux·运维·服务器
存储服务专家StorageExpert1 小时前
DELL SC compellent存储的四种访问方式
运维·服务器·存储维护·emc存储
说私域1 小时前
社群团购中的用户黏性价值:以开源小程序多商户AI智能名片商城源码为例
人工智能·小程序
长天一色2 小时前
【ECMAScript 从入门到进阶教程】第三部分:高级主题(高级函数与范式,元编程,正则表达式,性能优化)
服务器·开发语言·前端·javascript·性能优化·ecmascript
醉颜凉2 小时前
银河麒麟桌面操作系统修改默认Shell为Bash
运维·服务器·开发语言·bash·kylin·国产化·银河麒麟操作系统
前端张三3 小时前
Mac 电脑pink 后端ip地址进行本地联调
服务器·tcp/ip·macos
第六五3 小时前
ubuntu命令行连接wifi
服务器·ubuntu
CXDNW3 小时前
【网络篇】计算机网络——应用层详述(笔记)
服务器·笔记·计算机网络·http·web·cdn·dns
zeruns8023 小时前
如何搭建自己的域名邮箱服务器?Poste.io邮箱服务器搭建教程,Linux+Docker搭建邮件服务器的教程
linux·运维·服务器·docker·网站