8

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

3

3 Answers 3

15

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I want to upload a file without using php. I just want to know that, can I upload a file using js ?
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>

2 Comments

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/…
get error: e.target.files.forEach is not a function
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.

1 Comment

{ "message": "Uncaught ReferenceError: uploadFile is not defined", "filename": "stacksnippets.net/js", "lineno": 12, "colno": 67 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.