JS/html/form/XMLHttpRequest Ajax 批量上传文件/图片的3种方式
写在前面:后端选择你项目中使用的语言接收并处理图片。
由于上传图片都是以jQuery插件,为了纯js的崛起,遂选择ajax上传的方式,但在查找相关实例的时候着实困难重重,仅这个上传功能来回测试不下于2天的时间,最终还是执着战胜了困境。
以下3种方式都经多次测试通过。
重要说明:
第一种:切记:form -> enctype="multipart/form-data"
第二种:阻止默认submit:event.preventDefault();
第三种:var formData = new FormData();
formData.append('photos', file);
xhr.send(formData);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax文件上传</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <h1>1、纯HTML上传文件</h1> <input type="file" name="pic" accept="image/*"> <input type="submit"> </form> <form id="file-form"> <h1>2、JS post form file</h1> <input type="file" name="images" multiple accept="image/*"/> <button type="submit" name="btn">上传文件</button> </form> <div> <h1>3、JS Ajax post file</h1> <input type="file" id="files" name="photos" multiple accept="image/*"/> <button type="submit" id="upload">上传文件</button> </div> <script> // JS post form file var form = document.getElementById('file-form'); form.onsubmit = function(event) { event.preventDefault(); var files = form.images.files; var file = files[0]; var formData = new FormData(); formData.append('images', file); var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); xhr.onload = function () { if (xhr.status === 200) { // File(s) uploaded. form.btn.innerText = '上传成功!'; console.log('Upload Finished!!!!!!!!!!'); } else { alert('An error occurred!'); } }; xhr.send(formData); }; var files = document.getElementById('files'); var uploadBtn = document.getElementById('upload'); uploadBtn.onclick = function() { var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload', true); xhr.onload = function () { if (xhr.status === 200) { // File(s) uploaded. uploadBtn.innerHTML = 'Upload Finished'; } else { alert('An error occurred!'); } }; var file = files.files[0]; var formData = new FormData(); formData.append('photos', file); xhr.send(formData); } </script> </body> </html>
更多实例应用扫码体验:
相关推荐
wcqwcq 2020-07-04
TONIYH 2020-06-11
jiaguoquan00 2020-07-07
坚持着执着 2020-06-05
lyqdanang 2020-08-16
坚持着执着 2020-06-16
TONIYH 2020-06-05
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19