Posting Files
Check this guide (opens in a new tab) to learn more about using files.
-
Create a Next.js application then install and setup Prisma.
-
Create a model for storing a document with required name, type, size, and content properties:
prisma/schema.prismamodel File { id String @id @default(cuid(2)) name String size Int content Bytes type String }
-
Create an endpoint to upload files and store them in the database:
app/api/files/route.jsexport async function POST(request) { const formData = await request.formData(); const file = formData.get("file"); const content = Buffer.from(await file.arrayBuffer()); const result = await prisma.file.create({ data: { name: file.name, size: file.size, type: file.type, content, }, }); return Response.json(result.id, { status: 201 }); }
-
Design an interface to upload multiple files:
index.html<form> <label for="files-input">Upload</label> <input type="file" id="files-input" multiple="{true}" accept="*" /> </form> <script type="application/javascript"> document .querySelector("#files-input") .addEventListener("change", async (event) => { const files = event.target.files; for (let k = 0; k < files.length; k += 1) { const formData = new FormData(); formData.append("file", files[k]); const response = await fetch("/api/files", { method: "POST", body: formData, }); } event.target.value = ""; }); </script>
-
Display a link and a button to download/view and an another to delete an uploaded file.