How to upload a file using javascript?

2020-07-27 02:51发布

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

2条回答
Emotional °昔
2楼-- · 2020-07-27 03:10

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

<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 FilePond and this is very similar to how it does uploading as well.

查看更多
何必那么认真
3楼-- · 2020-07-27 03:21

You can use html5 file type like this:

<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

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

查看更多
登录 后发表回答