How to upload a file using javascript?

亡梦爱人 提交于 2019-12-09 23:00:18

问题


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


回答1:


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/




回答2:


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.



来源:https://stackoverflow.com/questions/51035478/how-to-upload-a-file-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!