File Upload with React & Flask
Written by Ashish Pandey and Arshpreet Wadehra
This is will be a very short article on File Upload with React and Flask.
Client : React Js, and for HTTP Request we will use Fetch API
Setting Up the Frontend Environment
npm create-react-app frontend
cd fileUpload
npm start
In /fileUpload/src/index.js
:
We will simply render the main <App/>
component.
In /fileUpload/src/App.js
:
This is the entry component that has the title and the <Main/>
component.
In /fileUpload/src/components/Main.jsx
:
The following component has a form with file upload input and file name input. Upon submitting, the handleUploadImage
function will be called. The function will alter state’s imageURL
of uploaded image which is used as the href property in image tag on the bottom.
Setting Up Backend
Backend: Flask (I assume that you have python and flask install. If not Follow this Flask Installation).
Use CORS for local development for production use Nginx and remove the last line. If you need more info about CORS and why are we using it then check this article CORS in detail and CORS MDN. If you want to share data between across two functions we need to use sessions in python. You can avoid the session (line 22) if you don’t need it. Flask is a bit particular about what all you can return. Kindly check the official documentation for that.
VOILA..!! You are good to go.
Happy coding and experimenting. Thanks