ASP NET upload image with jQuery and AJAX - javascript

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)
{
}

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);
});

How can I send a file and a string to my backend C# from JQuery Ajax?

My UI has one input for uploading file and one input for the file's name.
I want to get both file and its name from user at the same ajax request and upload the file with the gotten name to my server.
the question is how can I get both file (binary) and the file's name from user at the same request ?
here is my try but results in 400 error.
Function in C#:
public IActionResult UploadImage(IFormFile upload, string fileWithName)
{
//some code here
}
and here is my ajax:
$("#startUploading").on("click",function() {
var fileInput = $.trim($("#myfile").val());
var formData = new FormData();
formData.append('upload', $('#myfile')[0].files[0]);
formData.append('pathWithName', $("#fileAddressUploadTo").val());
$.ajax({
url: apiUrl+'/api/V1/Servers/UploadImage',
type: 'POST',
data: formData,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('token'));
},
cache: false,
processData: false,
contentType: false
});
});
400 error means bad request, but per my test I found it worked for me. So I'm afraid the issue in your code may relate to $('#myfile')[0].files[0], see my code below
<div>
<input type="file" id="uploadFile" />
<button id="btn4">upload</button>
</div>
$("#btn4").click(function(){
var form = new FormData();
var temp = $('#uploadFile').prop('files');
form.append("file",temp[0]);
form.append("name","myFile");
console.log(form);
$.ajax({
url: 'https://localhost:44321/hello/upload',
type: 'POST',
data: form,
cache:false,
contentType:false,//stop jquery auto convert form type to default x-www-form-urlencoded
processData:false,
success: function (d) {
alert(d)
}
});
});
public string upload(IFormFile file, string name) {
return "hello";
}

Send file to api using Ajax

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>

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
})
}
})
})

Multiple File Upload Ajax Request Issue

This currently works to upload one file, however when I try to upload more than one file it doesnt work, and it only uploads the first selected file from the browse button. Please help on how to make this accept multiple files selected?
function makeProgress(number){
var url = getRelativeURL("web/fileUpload");
var formData = new FormData();
formData.append('number', number);
formData.append('file', $('input[type=file]')[0].files[0]);
console.log("form data " + formData);
$.ajax({
url : url,
data : formData,
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
FileUploadVisible(true);
$('#attachmentModal').modal('hide')
$(':input','#attachmentModal').val("");
$("#pbarmain").hide();
$("#pbar").hide();
$("#actionPlanDiv").hide();
setObjectEnabled('#Upload',false);
},
error : function(err) {
FileUploadErrorVisible(true);
}
});
}
Thanks!
you have to create an object of the formdata and append the files input to it, using a files[] object in a loop...
fd = new FormData();
fls = document.getElementById('uplfiles').files; //length of files...
for(j=0;j<fls.length;j++){
fd.append('files[]', fls[j]); //note files[] not files
}
where 'uplfiles' is the name of the files field, replace it with yours...
this should work, thank me later..
This is what worked for me.
HTML
<input type="file" id="my_uploads" multiple>
JS
// upload img
$('#my_uploads').on('change', function(e) {
var formData = new FormData();
var files = $('#my_uploads').prop('files');
$.each(files, function(i, file) {
formData.append('my_uploads', file);
$.ajax({
type: 'POST',
url: 'process-upload.php',
cache: false,
contentType: false,
processData: false,
data : formData,
success: function(response){
console.log(response);
},
error: function(err){
console.log(err);
}
})
});
});

Categories