Send file to api using Ajax - javascript

Im trying to send file to api using ajax , but form-data always null in both cases mentioned below
<form id="myformdoc">
<input type="file" size="45" name="file" id="file">
</form>
<script>
$('#file').on("change", function () {
// var formdata = new FormData($('form').get(0));
let myForm = document.getElementById('myformdoc');
let formData = new FormData(myForm);
$.ajax({
url: url,
type: 'POST',
data: formdata ,
cache: false,
processData: false,
contentType: false,
success: function (color) {
;
},
error: function () {
alert('Error occured');
}
});
});
</script>
Any idea why form-data always null ?

Try adding multipart/form-data in contentType parameter.

You need to use
formData append to add files to your formData function.
Change your jQuery code to this below and it will work fine and you can get the files on your backend to save them.
If you have other inputs in your form you can append them as well if you like to.
formData.append('file', $(this)[0].files[0])
Demo:
$('#file').on("change", function() {
//Initialize formData
let formData = new FormData();
console.log($(this)[0].files)
formData.append('file', $(this)[0].files[0]) //append files to file formData
$.ajax({
url: 'url',
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(color) {
console.log(color);
},
error: function() {
alert('Error occured');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" size="45" name="file" id="file">
</form>

Related

$_FILES empty when upload multiple files with FormData from Ajax

The problem is that when I try to upload a single file the server gets the request and I see that $ _FILES actually contains the uploaded file.
On the other hand, when I try to upload more files, the request comes with $ _FILES completely empty.
<input type="file" name="images[]" id="images-input-file" accept="image/jpeg" multiple="multiple" hidden />
//In this case '$(this)' is the file input
var files = $(this)[0].files;
//Append data to Form Data
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("file-" + i, files[i]);
}
$.ajax({
method: "POST",
url: "/server/fnc/upload-images",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(res) {
console.log(res);
},
});
Maybe the best way to do this is to use the form submit like this:
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/server/fnc/upload-images",
data: new FormData(this),
contentType: false,
processData: false,
success: function(res){
console.log(res);
}
});
}));
else can you try this to test:
var formData = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
formData.append('file', file);
});

jQuery AJAX multiple files upload but send one file at a time to server using ajax

I have following html
<form id="submit-form">
<input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple>
<input type="submit">
</form>
I am uploading files using ajax using formdata. The thing is that I don't want to send all files in one go using ajax. Instead I want to send single file per ajax request.
To upload files I am using following jQuery code
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
$.ajax({
url: url,
type: 'post',
data: formData,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
})
You can just use forEach method of FormData:
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
formData.forEach(function(entry) {
if (entry instanceof File) {
var fileForm = new FormData()
fileForm.append('resume', entry)
$.ajax({
url: url,
type: 'post',
data: fileForm,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
}
})
})

Sending formdata for file upload using ajax

I am trying to upload an image by using form data with ajax. Though below line seems to be working fine and saving the image on my local machine.
<form ref='uploadForm' id='uploadForm' action='/tab10/uploadImage' method='post' encType="multipart/form-data">
<input type="file" class="btn btn-default" name="file" />
<input type='submit' class="btn btn-default" value='Broadcast Image' />
</form>
But when instead of specifying action as a form attribute, i try to make the call using ajax, things didn't seem to be working fine.Below is the code that i am using to make the post API call using ajax.
HTML
<form ref='uploadForm' id='uploadForm' encType="multipart/form-data">
Jquery
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Below is the code i am using for saving the image.
exports.uploadImage = function(req, resp) {
var res = {};
let file = req.files.file;
file.mv('./images/image', function(err) {
if (err) {
res.status = 500;
res.message = err;
// return res.status(500).send(err);
return resp.send(res);
}
res.status = 200;
res.message = 'File uploaded!';
return resp.send(res);
});
};
When i checked the request data in my uploadimage function, it seems that in the request, parameter called "files" is not being send in the later case.
I think you have to create FormData, after you can append the file to the formData, add an ID to the input <input type="file" class="btn btn-default" name="file" id="uploadFile"/>
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = new FormData();
formData.append('file',$('#uploadFile')[0].files[0]);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
});
use
$("#uploadForm").submit(function () {
var formData = new FormData(this);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Use this format to fire ajax.because file is multipart or jquery serialize() method not serialize multipart content,so we need to put it manual.
//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
enctype:"multipart/form-data",
url: "/tab10/uploadImage",
data: fileContent,
processData: false,
contentType: false,
success: function(response) {
}
});

ASP NET upload image with jQuery and AJAX

What I'm trying to do is theoretically simple: I want upload an image using ASP.NET, jQuery and AJAX, without submitting a form (this part is important).
So I have this:
HTML
<input type="file" accept="image/*" id="imguploader">
jQuery
var file_data = $("#imguploader").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
$.ajax({
type: "POST",
url: '#Url.Action("InsertImage", "Product")',
data: { file: form_data },
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
Controller
public ActionResult InsertImage(HttpPostedFileBase file) {
//blabla and the code to insert in the database.
return Content("");
}
What else I have tried:
// instead of using FormData, I tried to direclty capture the file using these:
var file = $("#imguploader").file;
//and
var file = $("#imguploader")[0].files;
//Same result (null).
The problem is that the file variable is always null no matter what. What I'm doing wrong? Can anybody helps?
You can manually set the FormData keys and values yourself.
<input type="file" name="imguploader" id="imguploader" />
<button id="btnUpload">Upload</button>
Create FormData and set a new key/value
$("#btnUpload").on("click", function(e) {
e.preventDefault();
var file = $("#imguploader").get(0).files[0];
var formData = new FormData();
formData.set("file", file, file.name);
$.ajax({
url: '#Url.Action("InsertImage", "Product")',
method: "post",
data: formData,
cache: false,
contentType: false,
processData: false
})
.then(function(result) {
});
});
The controller
[HttpPost]
public ActionResult InsertImage(HttpPostedFileBase file)
{
}

Sending files and other data using ajax

I am trying to send data to server which includes files and strings with ajax. My code in jsp is:
<html>
...
<body>
...
<form id="data" method="post" enctype="multipart/form-data">
<input name="classroomID" type="hidden" value="1" />
<input type="file" name="file" size="30" id="file" />
<button>Submit</button>
</form>
<script type="text/javascript"
src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script type="text/javascript" src='sendUpload.js'></script>
...
</body>
</html>
And my sendUpload.js looks like this:
$(document).ready(function() {
console.log("here");
$("form#data").submit(function(ev){
ev.preventDefault();
console.log("Submitted");
var formData = new FormData($(this)[0]);
console.log(JSON.stringify(formData));
$.ajax({
url: "UploadServlet",
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
But the JSON data is empty. any suggestions? I am using java servlet.
What kind of errors are you getting? Looks like your jquery selector is wrong, i'd try changing this:
$("form#data").submit(function(ev){
To this:
$("#data").submit(function(ev){
Not really sure though, you should post the specific errors.
$(document).ready(function() {
$("form#data").submit(function(e){
e.preventDefault();
$.ajax({
url: "UploadServlet",
type: 'POST',
data: {
classroomID: $('input[name="classroomID"]').val(),
file: $('input[name="file"]').val()
},
success: function (data) {
alert(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Does it work for you?
You can do this:
var formData = new FormData();
formData.append('classroomID', $('#classroomID').val());
formData.append('file', $('#file')[0].files[0]);
...and give your classroomID input field an id of 'classroomID'.
Also, you cannot inspect formData directly from the console so you will have to use this to debug:
for (var item of formData) {
console.log(item);
}

Categories