7

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

M Katz
  • 5,098
  • 3
  • 44
  • 66
Manjeet Kumar Nai
  • 1,382
  • 1
  • 13
  • 16
  • 1
    We cannot help you unless and until you've helped yourself. Post the code that you have tried. – Krishna Prashatt Jun 26 '18 at 05:40
  • 1
    possibly duplicate to https://stackoverflow.com/questions/5587973/javascript-upload-file/5587986#5587986 – Terry Wei Jun 26 '18 at 05:40
  • Possible duplicate of [JavaScript: Upload file](https://stackoverflow.com/questions/5587973/javascript-upload-file) – JJJ Jun 26 '18 at 06:52

3 Answers3

13

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/

Firemen26
  • 1,025
  • 12
  • 21
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>
Rik
  • 3,328
  • 1
  • 20
  • 23
  • 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. https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript#dealing_with_binary_data – 1.21 gigawatts Jun 15 '23 at 08:32
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.

Kartikeya Rana
  • 200
  • 3
  • 9
  • { "message": "Uncaught ReferenceError: uploadFile is not defined", "filename": "https://stacksnippets.net/js", "lineno": 12, "colno": 67 } – Boris Gafurov Aug 16 '23 at 16:38