I want to post a csv file to django view using jquery
<form id="form" enctype="multipart/form-data" >
<input type="file" name="ListFile" id="ListFile" />
<button type="button" onclick="csv_send">upload</button>
</form><br>
js is:
function csv_send(){
var data = {
'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val(),
'data': $("#ListFile").val()
}
/*$.ajax({
type: 'POST',
url:'/list/create/',
cache:false,
dataType:'json',
data:data,
success: function(result) {
console.log("ok")
}
});*/
}
django views.py:
def createlist(request):
if request.method == 'POST':
file = request.FILES
here not getting file.I know getting file using form action.But here i want to post file through javascript because i want response back to javascript after success.
Clearly i want that file in views.py by request.FILES
When uploading files, your form must have this attribute:
enctype='multipart/form-data'
like this:
<form id="form" enctype='multipart/form-data'>
This might help you understand.
You have to use a FormData object and a slightly modified version of basic ajax post:
var data = new FormData();
var file = null;
//when uploading a file take the file
$("#your-file-input-id").on("change", function(){
file = this.files[0]
});
//append the file in the data
data.append("file", file);
//append other data
data.append("message", "some content");
$.ajax({
url: '/path',
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function (data, status, xhr) {
//handle success },
error: function (data, status, xhr) {
//handle error
}
});
In Django you will find the file in request.FILES['file'].
I hope this is helpful.
Related
Say I have an array which contains a few images:
var images = [image1, image2, image3]
How do I send these images to a php file using AJAX in a single request?
The following code did not work:
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: {data: images},
success: function(data) {
alert(data);
location.reload();
}
});
My HTML:
<div id="newPostFile">
<label for="newPostFiles"><i class="fa fa-file-text-o" id="newPostFileIcon" aria-hidden="true"></i></label>
<input type="file" name="newPostFiles" id="newPostFiles">
</div>
Endgoal:
Whenever a file is selected, the file is added to the array and when the submit button is clicked, all the files are uploaded at once.
You have to send files as formData
var images = [image1, image2, image3]
var data = new FormData();
images.forEach(function(image, i) {
data.append('image_' + i, image);
});
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: data,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
location.reload();
}
});
But as you're reloading the page anyway, why use ajax at all ?
You can pass a JSON object to PHP, which would be the convenient solution here
var data ={'image1':image1,'image2':image2};
You can pass this object to the php code and then parse it:
Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'PHP/posts.php',
data : {result:JSON.stringify(data)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "image1 : ".$data["image1"];
Another option would be serializing the array before sending, or convert it into a comma separated string using array.join, then parse/split on the posts.php
array.join(",")
you can just use the list symbol after the input name [i]
for example:
let formData = new FormData();
let files = fileInput.prop('files');
for (let i = 0; i < TotalFiles; i++) {
formData.append('file['+i+']', files[i]);
}
Use FormData Object to send files using ajax.new FormData($('#your_form_id')[0]) automatically appends all form input in FormData object which we can be done by manually formData.append('file1',file1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
let formData = new FormData($('#your_form_id')[0]);
$.ajax({
url: 'PHP/posts.php',
type: 'POST',
data: formData,
dataType:'json',
processData: false,
contentType: false,
success: function(response) {
console.log(response);
location.reload();
},
error: function() {
console.log('fail');
}
});
</script>
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");
}
})
I am trying to create an image upload field in my application based on this question:
Send FormData and String Data Together Through JQuery AJAX?
and this tutorial:
http://www.formget.com/ajax-image-upload-php/
I have heard it is quite difficult, this is what i have tried.
HTML
<form method="POST" action="" id="logo_upload">
<input type="file" name="logo_location" id="logo_location" enctype="multipart/form-data">
<button type="submit" name="file_test" id="file_test">Test Upload</button>
</form>
JQuery
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData();
var file_data = $('#logo_location')[0].files[0];
formData.append("file", file_data[0]);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData ,
cache: false,
contentType: false,
processData: false,
id: id
});
});
PHP
var_dump($_FILES);
var_dump($_POST);
As you can see, I haven't got to the uploading side of things yet.
Result
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
I can't see what i am doing wrong, I am getting a result so it is getting to the right place, can anyone point me in the right direction?
EDIT: added #logo_upload in form
var file_data = $('#logo_location')[0].files[0];
EDIT: replaced data with formData variable
EDIT: added attribute: enctype="multipart/form-data"
New Result:
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
'file' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'undefined'</font> <i>(length=9)</i>
</pre>
You're appending file_data[0] to the formdata object, file_data is the file not an array, use file_data.
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData();
var file_data = $('#logo_location')[0].files[0];
formData.append("file", file_data);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData ,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
});
also you can instantiate the form data object with the form in question instead of doing the append.
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
...
I don't see logo_upload id in your form.
When uploading a file enctype="multipart/form-data" is must in form attributes.
data parameter in your ajax getting a variable i.e. not defined. Look at your reference link once again.
Hope this would help you
You are passing wrong variable here and you are not defining success in your ajax request:
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData($('#your_form_id')[0]);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData,
success: function(result){
alert(result);
}
cache: false,
contentType: false,
processData: false
});
});
I am trying to upload a csv file with spring boot 1.2.0 REST controller and jQuery ajax. When I send the post request, I keep getting 415:Unsupported Media type error. Here is my form:
<form id="upload_form">
<div id="message">
</div>
<br/>
<div class="row" id="upload-file-div" style="display: none">
<div class='col-sm-3'>
<label>Select File</label>
<input type="file" name="file">
</div>
<div class='col-sm-3'>
<input type="button" id="file-upload" class="btn btn-primary" value="Upload" onclick="uploadFile()"/>
</div>
</div>
</form>
Here is my method to upload file:
function uploadFile(){
var response = api.uploadCSV($("#upload_form"));
if(response.status === 'OK'){
$("#message").css('color', 'green');
}else{
$("#message").css('color', 'red');
}
$("#message").html(response.message);
}
Here is the actual jQuery POST:
upload: function (url, form, ignoreSuccess) {
var response = null;
if (!this.validate(form)) {
var array = form.serializeArray();
alert(array);
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
beforeSend: function (request) {
if (api.getSession() !== null) {
request.setRequestHeader("Authorization", "Bearer " + api.getSession().bearer);
}
},
success: function () {}
}).done(function (msg) {
response = msg;
});
}
return response;
}
Following is my controller:
#RequestMapping(consumes = "multipart/form-data", method = RequestMethod.POST,
value = "/upload/twitter", produces = MediaType.APPLICATION_JSON_VALUE)
public Response<String> uploadCsv(CsvUploadModel form) {
//Code
}
I have both MultipartConfigElement and MultipartResolver annotated in my spring boot class. I am using spring boot 1.2.0. When I send the post request with PostMan (chrome extension), it works as expected. However, when I try the above jquery code, it keeps throwing unsupported media type error.
Following things I have tried:
Playing around content-type header, finally I have set the contentType to false.
Using form.serializeArray(), iterating over it and appending individual elements into formData.
Sending the form object instead of form data.
Can anyone please help me with this? Thanks in advance.
You can append your file input in your formData; the following changes needs to be made:
This:
<input type="file" name="file">
Should be:
<input type="file" name="file" id="file">
And in your ajax code, this:
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Should be:
var formData = new FormData();
formData.add("file",$('#file')[0].files)
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Or:
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
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.