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)