How to upload file without form using JavaScript ?
There are several approaches to upload a file without using the form in JavaScript:
Approach 1: This approach is to use FormData that can upload a file without using any kind of form. The special thing about this is that network methods, such as fetch, can accept a FormData object as a body. It’s encoded and sent out with Content-Type — multipart/form-data.
JavaScript Snippet:
Javascript
var gfg = new FormData();
gfg.append('pictureFile',
pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: gfg
});
|
Approach 2: This approach is to use XMLHTTPRequest that can directly upload the file as the content inside the body of POST request.
JavaScript Snippet:
Javascript
var form = document.getElementById('the-form');
form.onsubmit = function () {
var formData = new FormData(form);
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
return false;
}
|
Approach 3: This approach is to use simpleUpload plugin.
HTML Code Snippet:
HTML
<!DOCTYPE html>
<html>
<body>
<h2>Welcome To GFG</h2>
<input type="file" name="arquivo"
id="simpleUpload" multiple>
<button type="button" id="upload">
Upload
</button>
</body>
</html>
|
JavaScript Snippet:
Javascript
$('#simpleUpload').simpleUpload({
url: 'upload.php',
trigger: '#upload',
success: function (data) {
alert('Successfully Uploaded');
}
});
|
Output:




Last Updated :
12 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...