In my project, I use Python Flask working as the server side and JS as the front end. The project allows user to select a photo and send the photo to the server side with AJAX post method. And server side will do image processing for this photo, and send back some data in JSON format about the image to the front end.
The JS code goes as following:
$(document).ready(function(){
$("form").submit(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '/upload',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: false,
success: function(result) {
var ctx = document.getElementById("result").getContext("2d");
res = JSON.parse(result)
var data = {
labels: res['sentiment'],
datasets: [
{
label: "Face Analysis",
fillColor: "white",
data: res['score']
}
]
};
var myLineChart = new Chart(ctx).Bar(data, {
showScale: false
});
},
});
return false; // so that form doesn't try to complete post
});
});
There is one confusing point for me, the final line return false
, what is its function? If I remove this line, the app will fail. I find this from other resource, although there is comment after that, still can't figure out the meaning?
The Flask route goes as below:
@app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
#print "post method"
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#return redirect(url_for('uploaded_file',filename=filename))
result = image_analysis(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print type(result)
return json.dumps({'sentiment':result.keys(),'score':result.values()})
#return json.dumps({'aftervalue':"baoqger"})