Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file using javascript?

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

like image 491
Manjeet Kumar Nai Avatar asked Jun 26 '18 05:06

Manjeet Kumar Nai


People also ask

Can we upload file using JavaScript?

html file through a browser, the client will be able to upload a file to the server using Ajax and pure JavaScript. A pure JavaScript file uploader simplifies Ajax based interactions with the server.

How do you upload a file in HTML code?

HTML allows you to add the file upload functionality to your website by adding a file upload button to your webpage with the help of the <input> tag. The <input type=”file”> defines a file-select field and a “Browse“ button for file uploads.

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .


2 Answers

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/

like image 148
Firemen26 Avatar answered Nov 01 '22 15:11

Firemen26


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>
like image 40
Rik Avatar answered Nov 01 '22 15:11

Rik