How to upload a file using javascript?
Asked Answered
P

3

8

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

Pitcher answered 26/6, 2018 at 5:32 Comment(3)
We cannot help you unless and until you've helped yourself. Post the code that you have tried.Tampa
possibly duplicate to https://mcmap.net/q/99246/-javascript-upload-file/…Dalmatian
Possible duplicate of JavaScript: Upload fileWestward
S
14

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/

Strum answered 26/6, 2018 at 5:48 Comment(1)
I want to upload a file without using php. I just want to know that, can I upload a file using js ?Pitcher
L
7

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>
Lorant answered 18/12, 2018 at 22:14 Comment(2)
I like MDN examples but I think that the example about this on MDN may be outdated. Can you confirm that the method you described is valid? I am using formData.append() the same as you and it is uploading. The example on MDN is manually creating the form data. developer.mozilla.org/en-US/docs/Learn/Forms/…Wisniewski
get error: e.target.files.forEach is not a functionSaharanpur
B
0

HTML Part:

<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:

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. In the JS function, I'm using the XMLHttpRequest to send the file.

A detailed step-by-step document can be found here.

Baro answered 26/5, 2021 at 16:27 Comment(1)
{ "message": "Uncaught ReferenceError: uploadFile is not defined", "filename": "stacksnippets.net/js", "lineno": 12, "colno": 67 }Helm

© 2022 - 2024 — McMap. All rights reserved.