elementui 手动上传文件 post 请求

发布时间 2023-07-03 11:25:37作者: 卢老师不想编程
// 上传图片校验
    fileChange(file) {
      const isJPG = file.raw.type === 'image/jpeg'
      const isPNG = file.raw.type === 'image/png'
      const isLt2M = file.raw.size / 1024 / 1024 < 0.2
      if (!isPNG && !isJPG) {
        this.fileList = []
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
        return false
      } else if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 200kb!')
        this.fileList = []
        return false
      } else if (isLt2M && (isPNG || isJPG)) {
        const obj = {
          url: file.url,
          raw: file.raw,
          name: file.name
        }
        this.fileList.push(obj)
        this.noneBtnImg = this.fileList.length >= this.limitCountImg
        this.picUpload(obj)
      }
    },
 
    picUpload(obj) {
      const formData = new FormData()
      formData.append('file', obj.raw)
      uploadPicture(formData).then((res) => {
        if (res.code === 200) {
          this.picUrl = res.data
        }
      })
    }
 
uploadService.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'multipart/form-data'
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)