javascript 如何使用javascript上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51035478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:23:43  来源:igfitidea点击:

How to upload a file using javascript?

javascriptfile-uploaduploaduploader

提问by Manjeet Kumar Nai

I want to create an uploader with js. Can anyone help me how to upload a file using javascript?

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

回答by Firemen26

You can use html5 file type like this:

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

<input type="file" id="myFile">

You file will be in value:

您的文件将有价值:

var myUploadedFile = document.getElementById("myFile").files[0];

For more information see https://www.w3schools.com/jsref/dom_obj_fileupload.asp

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

and see example here: https://www.script-tutorials.com/pure-html5-file-upload/

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

回答by Rik

You can upload files with XMLHttpRequestand FormData. The example below shows how to upload a newly selected file(s).

您可以使用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>

Disclaimer, I'm the author of FilePondand this is very similar to how it does uploading as well.

免责声明,我是FilePond的作者,这与它的上传方式非常相似。