Reputation: 53
I am trying to build an asynchronous file uploader with JS and Flask. So far the process of sending the file from JS to Flask seems to be working fine, but how to get any information from Flask back to JS afterward has been confusing. Specifically, I went to inform JS of the new URL of the uploaded file after upload completes. Here's what happens on the JS side when a file is uploaded:
let send_one_file = function(file) {
let filename = file.name;
var formData = new FormData();
var request = new XMLHttpRequest();
formData.append('file[]', file);
request.open('POST', '/upload');
request.send(formData);
request.onreadystatechange = function () {
if (request.readyState === 4)
if (request.status === 201) {
console.log(filename + " success!");
console.log('Response',request.response.data);
}
else {console.log(filename + " failed!");}
};
};
In the line console.log('Response',request.response.data);
I'm trying to get the string from the response object, which is sent from Flask like so:
@app.route("/upload", methods=['POST'])
def upload_file():
#at the moment nothing actually happens to the "uploaded" file
files = request.files.getlist("file[]")
response_data = {'path': "/files/"+files[0].filename,}
return Response(response=jsonify(response_data), status=201, mimetype='application/json')
JS detects the status of the response perfectly fine, but so far I can't figure out how to get it to read anything else. The request.response.data is "undefined."
Please let me know if I'm going about this entirely wrong. I've never built a web app before.
Upvotes: 1
Views: 2453
Reputation: 53
Here's what I ended up with.
JS:
let send_via_fetch = function (file) {
let formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.then(result => {
update_file_list(result['filename'], result['path'])
})
.catch(error => {
console.log('Error:', error);
})
};
Python:
@bp.route('/upload', methods=['PUT'])
@login_required
def upload():
f = request.files['file']
now = datetime.datetime.now()
destination = join(current_app.config["UPLOAD_FOLDER"], str(now.year), str(now.month))
if not isdir(destination):
makedirs(destination)
filename = secure_filename(f.filename)
path = join(destination, filename)
f.save(path)
response_data = jsonify({'path': path, 'filename':filename})
resp = make_response(response_data, 201)
return resp
Upvotes: 2