In my project I use Flask framework and JS on the front end, now I want to use AJAX post method to send a image to server side and save the image.
So far, based on some searching, I use FileReader() API to read the file in and generate a thumbnail on the web, this part can work well now. Then I want to continue sending the image to the server, but blocked here. I use $.AJAX
post method to send the image.
the js function goes as following:
var files = [];
function handleFileSelect(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var imgtag = document.getElementById("currentImage");
imgtag.title = selectedFile.name;
reader.onload = function(event) {
imgtag.src = event.target.result;
object = {};
object.filename = selectedFile.name;
object.data = event.target.result;
files.push(object);
};
reader.readAsDataURL(selectedFile);
};
$(document).ready(function(){
$("form").submit(function() {
alert("good");
$.each(files, function(index, file) {
$.ajax({url: "/image",
type: 'POST',
data: {filename: file.filename, data: file.data},
});
});
});
});
and since I don't know how to handle and get the image file, so the server side code I just try request.files
as following:
@app.route('/image',methods=['POST'])
def image_upload():
file = request.files['files']
print file.filename
I debug that the '/image' can get the post request, but have no idea about how to get the image from request
.
Edit: the HTML form part goes as following:
<form enctype="multipart/form-data">
<input type="file" id="files" name="files" onchange="handleFileSelect(event)"/>
<img id="currentImage" src="/static/1.jpg" alt="Mountain View" style="width:304px;height:228px;">
<input type="submit" value="Analyse the image v2">
</form>
Edit II: Find the solution in other ticket, the FormData object is the right answer in the following link: How to upload a file using an ajax call in flask