如何使用javascript上传文件?

Man*_*Nai 4 javascript upload file-upload uploader

我想用js创建一个上传器。谁能帮助我如何使用javascript上传文件?

Fir*_*n26 7

您可以像这样使用 html5 文件类型:

<input type="file" id="myFile">
Run Code Online (Sandbox Code Playgroud)

您的文件将有价值:

var myUploadedFile = document.getElementById("myFile").files[0];
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅https://www.w3schools.com/jsref/dom_obj_fileupload.asp

并在此处查看示例:https : //www.script-tutorials.com/pure-html5-file-upload/


Rik*_*Rik 7

您可以使用XMLHttpRequest和上传文件FormData。下面的示例显示了如何上传新选择的文件。

<input type="file" name="my_files[]" multiple/>
<script>
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {

  const fd = new FormData();

  // add all selected files
  e.target.files.forEach((file) => {
    fd.append(e.target.name, file, file.name);  
  });
  
  // create the request
  const xhr = new XMLHttpRequest();
  xhr.onload = () => {
    if (xhr.status >= 200 && xhr.status < 300) {
        // we done!
    }
  };
  
  // path to server would be where you'd normally post the form to
  xhr.open('POST', '/path/to/server', true);
  xhr.send(fd);
});
</script>
Run Code Online (Sandbox Code Playgroud)