Ajax上傳文件/照片時報錯TypeError :Illegal invocation

問題

Ajax上傳文件/照片時報錯TypeError :Illegal invocationhtml

clipboard.png

解決

網上搜索問題,錯誤緣由可能有如下幾個,依次檢查:jquery

  1. 請求類型有誤,如post請求,但在後臺設置的是get請求
  2. 參數有誤。 如沒有傳參,或是參數對應不上去
  3. File類型的參數被預先處理了

檢查後發現應該時緣由3,故修改代碼,設置$.ajaxprocessData: falseajax

getToken().then( res => {
  console.log('獲取七牛雲token後上傳圖片')
  if(!res.hasOwnProperty('data')) return
  // 整理參數
  var formData = new FormData()
  formData.append('token', res.data)
  formData.append('file', file)
  $.ajax({
    url: '',
    type: 'POST',
    contentType: 'multipart/form-data',
    processData: false,  // 增長這一行,不處理參數
    data: formData,
    success: function (result) {
      console.log(result)
    }
  })
})

參考

  1. 使用AJAX實現文件上傳時Illegal invocation錯誤
  2. jquery ajax報Uncaught TypeError :Illegal invocation
相關文章
相關標籤/搜索