π Upload File in NextJS without any Library π
So you're working on a Next.js project and need to implement a file upload feature without using any external libraries? π No problem! Next.js provides a straightforward way to achieve this. Let's dive into the code!
Create the Frontend Part
"use client"
import { useState } from "react"
export default function Home() {
const [file, setFile] = useState()
const onSubmit = async (e) => {
e.preventDefault();
console.log(file);
let data = new FormData();
data.set("file", file)
let res = await fetch("/api/upload/route", {
method: "POST",
body: data,
})
let response = await res.json()
console.log(response);
}
return (
<>
<form onSubmit={onSubmit}>
<input type="file" onChange={(e) => setFile(e.target.files[0])} />
<button type="submit">Upload</button>
</form>
</>
)
}
Create API file api/upload/route.js
import { writeFile } from 'fs/promises'
async function handler(req, res, next) {
let data = await req.formData()
console.log(data);
data = data.get("file");
let bytedata = await data.arrayBuffer()
let buffer = Buffer.from(bytedata)
let path = "./public/uploads/" + data.name;
await writeFile(path, buffer);
return Response.json("hi:hi")
}
export { handler as POST }
That's it! π Now you have a basic file upload setup in your Next.js app. When a user selects a file and hits the "Upload" button, the file is sent to the /api/upload/route
endpoint, where it's processed and saved to the public/uploads
directory.
It is recommended that use remote services like AWS or LINODE and don't upload files where your source code it there.
If you need more guidance, you can check out this video tutorial for a visual walkthrough. Happy coding! π
Top comments (1)
Thanks for sharing this, but wouldn't next bundle deploy remove all these files? I think this should be explicitly mentioned in the article to avoid confusion and manage expectations.