element ui-upload组件之上传图片封装upload.js文件

347 阅读1分钟

upload.js文件代码

这个文件可以放在项目中你想放在的位置

  1. aciton:这个属性配置的API就相当于一个中转站,把图片传上去 ,告诉后端 我要给你传个图片/文件
  2. hanldeUploadFile:方法中的接口是你获取到aciton返回的图片/文件数据,处理后传给这个接口,才是传给后端了
  3. 属性使用:http-request 或者before-upload 或者其他都是根据需求看你需要再上传文件的什么时候去选择即可
import request from '@/utils/request'  // 封装的Axios文件 
// 获取上传接口 这个就是el-upload中的aciton属性的接口
const getUpload = params => {
  return request({
    url: process.env.VUE_APP_BASE_FENG + '/minio',  //换成自己的API
    method: 'get',
    params
  })
}

// 上传文件
const uploadFile = (data, type) => {
  return request({
    url: data.url,
    method: 'put',
    data: data.file,
    headers: {
      upload: 'upload',
      'x-amz-acl': 'public-read',
      'Content-Type': type
    }
  })
}

// 上传处理回调
// _this:页面的this
// data:文件
// fileName:上传到后台以后,文件存放的文件名称
const dealWith = (_this, data, fileName, id) => {
  let _id = ''
  if (id) {
    _id = '/' + id + '/'
  } else {
    _id = '/'
  }
  return new Promise((resolve, reject) => {
    let fileNameOne = data.file.name.lastIndexOf('.') //取到文件名开始到最后一个点的长度
    let fileNameLength = data.file.name.length //取到文件名长度
    let fileFormat = data.file.name.substring(fileNameOne + 1, fileNameLength) //截去后缀名
    let suffixY = ''
    if (fileFormat == 'png') {
      suffixY = 'image/png'
    } else if (fileFormat == 'jpg') {
      suffixY = 'image/jpeg'
    } else if (fileFormat == 'gif') {
      suffixY = 'image/gif'
    } else if (fileFormat == 'doc' || fileFormat == 'docx') {
      suffixY = 'application/msword'
    } else if (fileFormat == 'pdf') {
      suffixY = 'application/pdf'
    } else if (fileFormat == 'json') {
      suffixY = 'application/json'
    }
    //修改文件名为时间戳
    let fileNamecutOut = data.file.name.substring(0, fileNameOne) // 对文件名进行切割(回去文件名)
    //新的文件名称
    // let fileNameTime = fileNamecutOut + Date.now() + '.' + fileFormat
    let fileNameTime = $utils.getUUID() + Date.now() + '.' + fileFormat
    let File = window.File
    try {
      new File([], '')
    } catch (e) {
        File = class File extends Blob {
        constructor(chunks, filename, opts = {}) {
          super(chunks, opts)
          this.lastModifiedDate = new Date()
          this.lastModified = +this.lastModifiedDate
          this.name = filename
        }
      }
    }
    let renameFile = new File([data.file], fileNameTime, { type: data.file.type })
    getUpload({ bucketName: fileName, objectName: _id + fileNameTime })
      .then(res => {
        if (res.code !== 200) return this.$message.error(res.msg)
        uploadFile({ url: res.data.uploadPath, file: renameFile }, suffixY)
          .then(data => {
            _this.$message.success(data.msg)
            // let url = res.data.split('?')
            resolve(res.data.downloadPath)
          })
          .catch(err => {
            console.log('uploadFile err', err)
          })
      })
      .catch(err => {
        console.log('uploadFile err', err)
      })
  })
}

export default {
  getUpload,
  uploadFile,
  dealWith
}
axios.put(this.uploadPath, 
  this.renameFile, {
          headers: {
  			'Content-Type': suffixY,
  			upload: 'upload',
      		'x-amz-acl': 'public-read'
          },
        }).then(res=>{
  		console.log('oss上传请求返回的图片res=>',res.data.uploadPath)
  })

upload.js如何使用

  1. 使用el-upload的文件中,引入upload.js
import uploadAPI from '@/api/common/upload.js'
<el-upload 
    ref="uploadTemplate" 
    :http-request="hanldeUploadFile" 
    size="mini"
    :show-file-list="false" 
    :action="'#'" 
    accept="你要上传的文件/图片后缀" 
    :limit="1"
    :disabled="false" 
    :data="{ uploadFolderPath: true }" // data属性:上传时附带的额外参数,根据需求使用
    >
 </el-upload>
 
 
hanldeUploadFile(param) {
// this, param.file, 'mcms', null这四个是要传给upload.js文件中dealWith这个方法的参数,没有的设置null
    uploadAPI.dealWith(this, param.file, 'mcms', null).then(async res => {
            const { code, msg } = await uploadTemplate(
            { //  上传图片传给后端接口的参数
                fileName: param.file.name.split('.')[0], 
                fileUrl: res[0].fileUrl, 
                fileType: res[0].fileType 
            })
            if (code !== 200) return this.$message.error(msg)
            this.$message.success(msg)
            this.$refs.uploadTemplate.clearFiles()
            this.list()
    })
   }