File not sending with FormData in Ajax request - javascript

I have an ajax request that is sending a file along with some other info. Everything except the file is the correct value, and the file is always null. I can't figure out why.
Here is the input I have included in the form:
<input type="file" id="file" runat="server"/>
On button click, it calls this function:
function ButtonClick() {
var file = document.getElementById('file').files[0]; // correctly gets the file
var formData = new FormData();
formData.append('key1', 'val1');
formData.append('key2', 'val2');
formData.append('file', file, file.name);
$.ajax({
cache: false,
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function (data, textStatus, jqXHR) { closeWindow(); },
timeout: 30000,
type: 'POST',
url: '<%= ResolveClientUrl("~/api/Example/ExampleUrl") %>'
});
}
When I receive the request server-side, I get the following values:
var key1= HttpContext.Current.Request.Form["key1"]); // returns "val1"
var key2= HttpContext.Current.Request.Form["key2"]); // returns "val2"
var file= HttpContext.Current.Request.Form["file"]); // returns "null"
And when I take a look at HttpContext.Current.Request.Form, "file" is not in the request at all.

The file should be accessible via
HttpContext.Current.Request.Files["file"]

Related

FormData in multiple ajax request files

I'm trying to do a Ajax's loops requests for send files to an API but i don't not what I send at Ajax's data. When I do only file in upload I use the own formdata object and works very well. I tried use loop and each row send an individual file but it's doesn't works too:
Multiple files:
var form_data = new FormData();
for(i=0;i<3;i++){ // 3 length just for tests
form_data.append('file', $('#myfile').prop('files')[i]);
}
for (var value of form_data.values()) {
$.ajax({
url: 'URI',
data: value,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert("Success!")
},
error: function(e){
alert("Error")
}
});
}

Ajax send array and Image in same request

I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})

Sending file data with ajax form submit

I have got issue sending file to a server with ajax for submitting. I tried lots of methods with var xhr = new XMLHttpRequest(); and $.ajax({}); but always its gives error Uncaught TypeError: Illegal invocation. I also use processData: false, but in this condition I got all form fields apart file field.
My Code for ajax is:
var fd = new FormData();
fd.append( 'file', $('#file')[0].files[0] );
fd.append( 'name', 'test');
$.ajax({
url: "uploadFile.php",
data: fd,
cache: false,
contentType: false,
// processData: false,
type: 'POST',
success: function(data, textStatus, jqXHR){
console.log('success');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('error');
}
});
In this I got only name field with value test in output, but not file.
Somebody please let me know where I am wrong.
Set contentType to specific format instead of false.
For eg. in case of image set it to :- "image/jpeg" etc.

JQuery ajax call on same domain not sending cookies when data is sent

I am trying to test whether we can convert our existing file upload form into a more ajax/html5 without changing much of the backend. So here is what I am doing on the test:
function sendFile() {
var data = new FormData();
var file = $('input[type=file]').get(0).files[0];
data.append("file1",file);
$.ajax({
type: 'post',
url: '/upload.jsp',
data: data,
contentType: 'multipart/form-data',
processData: false
});
}
So the file sending part is not the problem. The problem is that I am not getting any of my cookies. If I take the data: data param out then it sends the cookies just fine.
Any idea why?
Thanks.
You need to set the withCredentials $.ajax() setting:
function sendFile() {
var data = new FormData();
var file = $('input[type=file]').get(0).files[0];
data.append("file1",file);
$.ajax({
type: 'post',
url: '/upload.jsp',
data: data,
contentType: 'multipart/form-data',
processData: false,
xhrFields: {
withCredentials: true
}
});
}

POST data using AJAX POST

Is it possible to post image file using the jQuery's ajax post method. Would it work if I just put the file data in the POST request's 'data' parameter?
I am using django framework. This is my first attempt:
$('#edit_user_image').change(function(){
var client = new XMLHttpRequest();
var file = document.getElementById("edit_user_image");
var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
/* Create a FormData instance */
var formData = new FormData();
formData.append("upload", file.files[0]);
client.open("post", "/upload-image/", true);
client.setRequestHeader("X-CSRFToken", csrftoken);
client.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=frontier");
client.send(formData); /* Send to server */
});
The problem with this is that I don't get the'request.FILES' object on the serer side in my 'views.py'.
I also tried doing it with ajax post but it doesn't work either.
$('#edit_user_image').change(function(){
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:document.getElementById("edit_user_image").files[0],}
$.post("/upload-image/", data, function(){
});
});
Edit from one of the answers:
$('#edit_user_image').change(function(){
var formData = new FormData($("#edit_user_image")[0]);
$.ajax({
type: "POST",
url: "/upload-image/",
xhr: function() { // custom xhr
// If you want to handling upload progress, modify below codes.
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: formData,
// Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr) {
// If you want to make it possible cancel upload, register cancel button handler.
$("#yourCancelButton").click(xhr.abort);
},
success: function( data ) {
// Something to do after upload success.
alert('File has been successfully uploaded.');
location.reload();
},
error : function(xhr, textStatus) {
// Something to do after upload failed.
alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText);
}
});
});
This is my final working solution:
$('#edit_user_image').change(function(){
var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
var formData = new FormData($("#edit_user_image")[0]);
var formData = new FormData();
formData.append("file", $('#edit_user_image')[0].files[0]);
formData.append("csrfmiddlewaretoken", csrftoken);
$.ajax({
type: "POST",
url: "/upload-image/",
data: formData,
contentType: false,
processData: false,
});
});
You can if you use FormData, otherwise you have to use Flash or iframes or Plugins (these ones use flash or iframes), FormData comes with HTML5 so it won't work in IE <= 9, a great guy created a replica of FormData for old browsers, to use it you only have to put formdata.js in the head tag. So in my opinion you have to use FormData.
We say you have a form like this:
<form method="POST" name="form" id="form" enctype="multipart/form-data">
<input type="file" id="img"/>
<input type="submit"/>
</form>
you have to get the img chosen by the user so your javascript have to look like this:
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var data = new FormData($('form').get(0));
$.ajax({
url: :"/URL",
method: "POST",
data: data,
success: function(data){},
error: function(data){},
processData: false,
contentType: false,
});
});
});
and now you are going to be able to retrieve the img chosen by the user in django with:
request.FILES
Yes. You can post your image file using jQuery's ajax.
Try below code snippet.
// Your image file input should be in "yourFormID" form.
var formData = new FormData($("#yourFormID")[0]);
$.ajax({
type: "POST",
url: "your_form_request_url",
xhr: function() { // custom xhr
// If you want to handling upload progress, modify below codes.
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: formData,
// Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr) {
// If you want to make it possible cancel upload, register cancel button handler.
$("#yourCancelButton").click(xhr.abort);
},
success: function( data ) {
// Something to do after upload success.
alert('File has been successfully uploaded.');
location.reload();
},
error : function(xhr, textStatus) {
// Something to do after upload failed.
alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText);
}
});
My suggestion is add "return false after the ajax block.

Categories

Resources