Express backend server app to handle file uploads. React frontend.
*** Note: to open web links in a new window use: ctrl+click on link**
-
Uploads an image file from the React frontend. This file is fetched by the backend using express.jsm and stored in a files directory in the public folder.
-
The frontend uses a FormData object with inputs for the file itself and a file name. The image will be displayed on the frontend.
-
Node.js v12.3.1 javascript runtime using the Chrome V8 engine.
-
React v16.10.2 Frontend javascript library.
-
Runs the app in development mode. Open http://localhost:3000 to view in browser.
-
The page will reload if you make edits. You will also see any lint errors in the console.
- Runs the backend in development mode. Open http://localhost:8000 to view in browser.
- extract of Frontend
Main.js
that handles the file upload.
// function to upload an image. FormData() constructor used to create a new FormData object.
// file will be fetched by the backend server running on port 8000.
handleUploadImage(event) {
event.preventDefault();
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('filename', this.fileName.value);
fetch('http://localhost:8000/upload', {
method: 'POST',
body: data,
}).then((response) => {
response.json().then((body) => {
this.setState({ imageURL: `http://localhost:8000/${body.file}` });
});
});
}
-
Status: updated oct 2019. working front-end. When running back-end gives a 404 error message 'file not found'.
-
To do: check backend code.
-
Medium article by Antonio Erdeljac, jan 2018: File upload with Node & React
-
Signet article (original) by Antonio Erdeljac: File upload with Node & React
Repo created by ABateman - feel free to contact me!