1. π Install the necessary dependencies on your server
To get started, install the multer
package by running the following command:
npm install multer
2. π Add endpoints for image upload and access
We will create two endpoints: POST /api/images
for uploading images from our frontend and GET /images/{imageName}
to access the uploaded images.
Here's an example code snippet for these endpoints:
// index.js
import { createReadStream } from "fs";
import multer from "multer";
const upload = multer({ dest: "images/" });
// app.use('/images', express.static('images'))
app.get("/images/:imageName", (req, res) => {
// do a bunch of if statements to make sure the user is
// authorized to view this image, then
const imageName = req.params.imageName;
const readStream = createReadStream(`images/${imageName}`);
readStream.pipe(res);
});
app.post("/api/images", upload.single("image"), (req, res) => {
const imageName = req.file.filename;
const description = req.body.description;
// Save this data to a database probably
console.log(description, imageName);
return res.send({ description, imageName });
});
React code
1. β¨ Create an image uploader component in React
In the component, we will define a submit function that makes the API request in the parent component. This makes the component reusable.
The submit function should accept the event (e), the file, and a description of the image.
// components/FileUploader.jsx
import { useState } from "react";
function FileUploader({ submit }) {
const [file, setFile] = useState();
const [description, setDescription] = useState("");
return (
<div className="row">
<form onSubmit={e => submit(e, file, description)}>
<input
filename={file}
onChange={e => setFile(e.target.files[0])}
type="file"
accept="image/*"
></input>
<input
onChange={e => setDescription(e.target.value)}
type="text"
></input>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default FileUploader;
2. β¨ Implement the component
import axios from "axios";
import FileUploader from "./Components/FileUploader";
function App() {
const sendImage = async (e, file, description) => {
e.preventDefault();
const formData = new FormData();
formData.append("image", file);
formData.append("description", description);
const result = await axios.post(
"http://localhost:8080/api/images",
formData,
{
headers: { "Content-Type": "multipart/form-data" },
}
);
console.log(result.data);
};
return (
<>
<FileUploader submit={sendImage} />
</>
);
}
export default App;
Enjoy!
Now it's time to turn on your servers and start using this image uploader in your application. π
Note: The multer package has multiple configurations, such as handling multiple files, setting file size limits, and more. In this tutorial, we will keep it simple and focus on the basics.
If you found this content helpful, please let me know in the comments section and don't forget to follow me on Instagram @gregglatines. π
Top comments (0)