Last active
August 2, 2020 00:27
-
-
Save skwzrd/ee46cf69a24400a704c2bc1a6e7f59f2 to your computer and use it in GitHub Desktop.
Upload a File from React to a Flask API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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