Issue
I've tried a few things but the only answers I can find are from 2013. I've seen some people say it only worked on 1.6 Jquery but im not sure
Tried
<div class="form-group d-flex justify-content-center p-2 w-100" class="create-post-forms">
<fieldset>
<label id="add_photo_button" for="uploadImage" class="w-50 me-1"> <div class="btn btn-primary w-100 border-0 ">Add Photo</div> </label>
<input type="file" id="upload_file" name="postphoto" style="display: none">
</fieldset>
</form>
Javascript / Ajax
var photo = new FormData($('#post_info')[0]);
console.log(photo)
( ive also tried photo.get("myPhoto))
$.ajax({
type: "POST",
dataType: "json",
url: "/make_post_ajax",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ myPhoto : photo,}),
success: function(data) {
console.log(data)
}
});
Flask
photo = request.files.get('myPhoto')
And the Result is:
None
Solution
You have to decide whether you want to send form data or JSON. A combination of both fails.
The following example shows you how to send the entire form to the server via AJAX. Please note that the content type is not set and the data is not processed. Only then will the form be sent in 'multipart/form-data' format, as is necessary for uploading a file.
<form name="my-form">
<fieldset>
<label for="upload-image">Add Photo</label>
<input type="file" id="upload-image" name="my-photo" />
</fieldset>
<button type="submit">Submit</button>
</form>
$(document).ready(() => {
$('form[name="my-form"]').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: '/make_post_ajax',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
}).done(function() {
console.log('Successful uploaded photo.');
});
})
});
@app.post('/make_post_ajax')
def upload():
file = request.files.get('my-photo')
if file:
print(file)
return ''
abort(400)
If you want to use JSON, I recommend converting the image data into a Base64 string before sending it.
Answered By - Detlef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.