JS native Ajax upload the main code

var form = new new the FormData (); 
form.file = File;     // File event file is obtained from a change in the input box file content 
var uploadURL with = '/ Upload / Images /';     // uploaded path 
the try {
   var XHR;
   IF (window.XMLHttpRequest) { 
    XHR = new new the XMLHttpRequest (); 
  } the else  IF (window.ActiveXObject) { 
    XHR = new new the ActiveXObject ( "Microsoft.XMLHttpRequest" ); 
  } the else { 
    console.warn ( 'browser version ' , 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);
}

Reference links: JS file upload principle (form form, FormData + XHR2 + FileReader + canvas )

Guess you like

Origin www.cnblogs.com/mengyouyouyou/p/11982920.html