天天看點

通過api接口把圖檔上傳給後端(踩坑)

1.加multipart/form-data

//使用者端圖檔上傳  加multipart/form-data
export const uploadImage = (params) => {
  return $.post('/app/pat/pushpull/imgUpload', params, { headers: { "Content-Type": "multipart/form-data" } })
}
           

 2.還有最主要用 new FormData 來傳。。。。

async getImageByHost (file, field) {
      console.log(111, file)
      let File = new FormData()
      File.append("file", file)
      File.append("type", "Copy")
      
      const [err, res] = await to(uploadImage(File))
      if (err) return this.$toast(err.errorMsg)
      console.log(2222, res)
      if (!res) {
        this[field] = []
      }
      return res
    }
           
//上傳前通用限制 
function beforeUpload(file: any) {
    // 限制圖檔 格式、size、分辨率
    const isJPG = file.type === "image/jpeg"
    const isJPEG = file.type === "image/jpeg"
    const isGIF = file.type === "image/gif"
    const isPNG = file.type === "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!(isJPG || isJPEG || isPNG)) {
      Modal.error({
        title: "隻能上傳JPG、JPEG、PNG格式的圖檔~",
      })
    } else if (!isLt2M) {
      Modal.error({
        title: "圖檔超過2M限制,不允許上傳~",
      })
    }
    return (isJPG || isJPEG || isPNG) && isLt2M

  }