JS 原生Ajax 上傳文件主要代碼


var form = new FormData();
form.file = file;    //file是從文件輸入框的change事件中獲取到的文件內容
var uploadUrl = '/upload/images/';    //上傳的路徑
try{
  var xhr;
  if(window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  }else if(window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHttpRequest");
  }else {
    console.warn('瀏覽器版本太低',err);
    return;
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      const result = JSON.parse(xhr.responseText);
      if (xhr.status === 200) {
        // 上傳成功
        console.log(result);
      } else {
        // 上傳失敗
      }
    }
  };

  xhr.withCredentials = false;
  xhr.open("POST", uploadUrl, true);
  xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  xhr.setRequestHeader("Content-Type","multipart/form-data");
  xhr.send(formData);
}catch(err) {
  console.warn('錯誤:',err);
}

參考鏈接:js文件上傳原理(form表單 ,FormData + XHR2 + FileReader + canvas)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM