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>

更多实例应用扫码体验:

JS/html/form/XMLHttpRequest Ajax 批量上传文件/图片的3种方式

相关推荐