I am new to web development and have a small web app where I need a user to upload a cropped image. My issue is that I cannot fetch the image that is send in the jQuery post request.
My Javascript and HTML looks like this:
function sendImage(imageData) {
var info = {}
info.upload = imageData
info.gender = gender.value
info.ageGroup = ageGroup.value
$.ajax({
type: "POST",
url: "/uploadToS3",
data: info,
enctype: 'multipart/form-data',
dataType: "json",
success: console.log("image written")
});
}
<div class="image-editor">
<input type="file" class="cropit-image-input">
<div class="cropit-preview"></div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<button class="export">Export</button>
</div>
Here is the python code handling the post request
#app.route('/uploadToS3', methods = ['POST'])
def uploadToS3():
username = session.get('username')
image = request.files.get('upload')
gender = request.form['gender']
ageGroup = request.form['ageGroup']
fileName = getNewFileName()
print(image)
return redirect('/')
image prints as 'None', the issue seems to be in the line where I request the upload parameter. The data being posted to Flask (taken from the form data) is upload:data:image/png;base64 and a very long string. So it looks like it posting correctly.
Any hints would be greatly appreciated
According to the answers to this question you can't just use an simple object as data when passing files.
For that purpose you have to do the following:
var formData = new FormData();
formData.append("gender",gender.value); // And so on...
formData.append("upload",$("#file")[0].files[0]); // When your file input has id="file"
$.ajax({
type: "POST",
url: "/uploadToS3",
data: formData,
enctype: 'multipart/form-data',
// And so on...
});
Related
HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}
This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 6 years ago.
I want to upload image without page loading, here sendImageFile is the value of file field. Now when I trying to upload any file from file_upload_to_user.php but every time $_FILES["sendImageFile"]["name"] returns null value.
<form enctype="multipart/form-data" method="post" name="img_upload_form" id="img_upload_form" action="file_upload_to_user.php">
<input name="sendImageFile" id="sendImageFile" type="file" accept=".png, .jpg, .jpeg"/>
<input type="submit" name="photoUploadToSend" id="photoUploadToSend" style="display:none" />
</form>
JS
var frm = $('#img_upload_form');
frm.submit(function (ev) {
var sendImageFile = document.getElementById("sendImageFile").value;
var to_hash = "000000000";
var dataString = 'sendImageFile='+sendImageFile+"&to_hash="+to_hash;
$.ajax({
type:"POST",
url:"file_upload_to_user.php",
data:dataString,
cache:false,
success: function(info) { alert(info);}
});
}
document.getElementById("sendImageFile").onchange = function change(){
// Upload image
document.getElementById("photoUploadToSend").click();
}
If you want to upload a file with ajax then you have to do it with FormData. And to send a formData with jQuery you need to send two other properties to to disable sending wrong stuff. so it's just easier to use fetch...
var form = document.getElementById("img_upload_form")
var fd = new FormData(form)
fetch("file_upload_to_user.php", {method: 'POST', body: fd})
To send a formdata with jQuery ajax you have to set this two:
processData: false,
contentType: false,
You need to use formData
var formData = new FormData();
formData.append('file', $('#sendImageFile')[0].files[0]);
formData.append('to_hash',"000000000");
$.ajax({
url : 'file_upload_to_user.php',
type : 'POST',
data : formData,
processData: false,//prevent automatic processing
contentType: false,//do not set any content type header
success: function(info) { alert(info);}
});
I don't really know what's going on here. Every time I try to upload a file, all the file contains is:
------WebKitFormBoundaryJ0uWMNv89fcUsC1t--
I have searched for the past 2 days for some sort of explanation, but I am just going in circles. I have no idea why this is happening.
Form:
<form id="upload-file" ecntype="multipart/form-data">
<input name="picture" type="file">
<input type="button" value="Upload" id="upload-button" />
</form>
Javascript:
$('#upload-button').click(function(e){
e.preventDefault();
var formData = new FormData($('#upload-file'));
$.ajax({
url: '/image',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
cache: false,
// contentType: false,
processData: false
});
});
Controller:
def image = Action(parse.temporaryFile) { request =>
request.body.moveTo(new File("/tmp/picture"))
Ok("File uploaded")
}
The problem was occuring in the Javascript, not the Scala. I was not referencing the form elements improperly.
var formData = new FormData($('#upload-file')[0]);
However, I also had problems with parse.temporaryFile and it was not properly storing the file using the code above. When I inspected the stored files in a text editor, I noticed it still had the ------WebKitFormBoundaryJ0uWMNv89fcUsC1t-- stuff at the beginning of the file, followed by the form information, then followed by the file bytes.
To fix this, I just used the default method for multipartform upload as per the Play Documentation, and it worked perfectly.
def image = Action(parse.multipartFormData) { request =>
request.body.file("picture").map { picture =>
val filename = picture.filename
picture.ref.moveTo(new File(s"/tmp/picture/$filename"))
Ok("ok")
}.getOrElse {
InternalServerError("file upload error")
}
}
I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not ajax.
here is my code:
html:
<div id="uploadPic" onclick="getFile()">
Select a photo to upload
</div>
<form name="myForm" id="avatar_form" enctype="multipart/form-data" method="post" action="">
<div style='height: 0px;width:0px; overflow:hidden;'>
<input id="upfile" class="botpic" type="file" name="avatar" value="upload" required="" onchange="sub1()">
</div>
</form>
javascript:
function getFile(){
document.getElementById("upfile").click();
}
function sub1(){
var photo = document.getElementById("upfile");
var file = photo.files[0];
data = new FormData();
data.append('file', file);
$.ajax({
url: 'url',
data: data
enctype: 'multipart/form-data',
processData: false, // do not process the data as url encoded params
contentType: false, // by default jQuery sets this to urlencoded string
type: 'POST',
success: function ( output ) {
document.getElementById('picTmp').innerHTML = output;;
}
});
}
PHP code:
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
.......
}
The first thing I notice is that you're missing a comma after the data parameter declaration. That might be your only issue.
$.ajax({
url: 'url',
data: data,
enctype: 'multipart/form-data',
//etc...
What's the name of your PHP script? That's what you should specify as 'url':
url: 'script_name.php',
Maybe this plugin could help you
Jquery Form
I had a lot of problem making from myself and with this plugin everething works, just try, this
$('form').ajaxForm(function() {
alert("Thank you for your comment!");
});
I would guess that without using preventDefault() method in your script,
you submit the form to the same page using action="" and method="post", thus never entering your $.ajax();
I've done something like this
$('#query_projects').submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
var request = $.ajax({
type: 'POST',
url: 'query_tab_projets.php',
mimeType:'application/json',
dataType:'json',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert(JSON.stringify(data,null,4));
},
error: function(msg){
alert(JSON.stringify(msg,null,4));
}
});
});
where #query_projects is my form id
Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly.
The solution is:
In the php code, all the ["avatar"] should be replaced with ["file"] as we are sending the file specified as file in ajax.
I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});