Skip to content

Instantly share code, notes, and snippets.

@skwzrd
Last active August 2, 2020 00:27
Show Gist options
  • Save skwzrd/ee46cf69a24400a704c2bc1a6e7f59f2 to your computer and use it in GitHub Desktop.
Save skwzrd/ee46cf69a24400a704c2bc1a6e7f59f2 to your computer and use it in GitHub Desktop.
Upload a File from React to a Flask API
# the flask post request receiver
from io import BytesIO
from flask import jsonify, request
@app.route('/url_route', methods=['POST'])
def upload_file():
"""Handles the upload of a file."""
d = {}
try:
file = request.files['file_from_react']
filename = file.filename
print(f"Uploading file {filename}")
file_bytes = file.read()
file_content = BytesIO(file_bytes).readlines()
print(file_content)
d['status'] = 1
except Exception as e:
print(f"Couldn't upload file {e}")
d['status'] = 0
return jsonify(d)
// the react post request sender
uploadFile = async (e) => {
const file = e.target.files[0];
if (file != null) {
const data = new FormData();
data.append('file_from_react', file);
let response = await fetch('/url_route',
{
method: 'post',
body: data,
}
);
let res = await response.json();
if (res.status !== 1){
alert('Error uploading file');
}
}
};
// the react form
<form>
<input
type="file"
onChange={this.uploadFile}>
</input>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment