简体   繁体   English

如何使用javascript上传文件?

[英]How to upload a file using javascript?

I want to create an uploader with js.我想用js创建一个上传器。 Can anyone help me how to upload a file using javascript?谁能帮助我如何使用javascript上传文件?

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/

You can upload files with XMLHttpRequest and FormData .您可以使用XMLHttpRequestFormData上传文件。 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.免责声明,我是FilePond的作者,这与它的上传方式非常相似。

HTML Part: HTML部分:

 <form enctype = "multipart/form-data" onsubmit="return false;" > <input id="file" type="file" name="static_file" /> <button id="upload-button" onclick="uploadFile(this.form)"> Upload </button> </form>

JavaScript Part: JavaScript 部分:

 function uploadFile(form){ const formData = new FormData(form); var oOutput = document.getElementById("static_file_response") var oReq = new XMLHttpRequest(); oReq.open("POST", "upload_static_file", true); oReq.onload = function(oEvent) { if (oReq.status == 200) { oOutput.innerHTML = "Uploaded!"; console.log(oReq.response) } else { oOutput.innerHTML = "Error occurred when trying to upload your file.<br \\/>"; } }; oOutput.innerHTML = "Sending file!"; console.log("Sending file!") oReq.send(formData); }

In the above HTML, I'm using the form to capture the files and calling the JS function when the button is clicked.在上面的 HTML 中,我使用表单来捕获文件并在单击按钮时调用 JS 函数。 In the JS function, I'm using the XMLHttpRequest to send the file.在 JS 函数中,我使用 XMLHttpRequest 发送文件。

A detailed step-by-step document can be found here .可以在此处找到详细的分步文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM