I want to create an uploader with js. Can anyone help me how to upload a file using javascript?
Asked
Active
Viewed 3.5k times
5
-
1We 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
-
1possibly 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 Answers
9
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
- 947
- 11
- 20
-
I want to upload a file without using php. I just want to know that, can I upload a file using js ? – Manjeet Kumar Nai Jun 13 '19 at 12:27
5
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
- 2,883
- 1
- 18
- 22
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
- 170
- 3
- 9