File uploads in Next.js
Two early patterns for handling uploads in a Next.js API route.
This is an archive of two upload patterns from an early Next.js project: writing files to the server filesystem and sending them to a Dropbox app folder. Both examples disable Next.js body parsing so Multer can consume the multipart stream.
Upload to the server filesystem
// pages/api/upload.ts
import nextConnect from "next-connect"
import multer from "multer"
const apiRoute = nextConnect({
onError(error, req, res) {
res.status(501).json({
error: `Sorry something Happened! ${error.message}`,
})
},
onNoMatch(req, res) {
res.status(405).json({ error: `Method '${req.method}' Not Allowed` })
},
})
const upload = multer({
storage: multer.diskStorage({
destination: "./public/uploads",
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + file.originalname)
},
}),
})
apiRoute.use(upload.array("file"))
apiRoute.post((req, res) => {
res.status(200).json({ data: "success" })
})
export default apiRoute
export const config = {
api: {
bodyParser: false,
},
}
Upload to Dropbox
import nextConnect from "next-connect"
import multerDbx from "multer-dropbox"
import multer from "multer"
import { Dropbox } from "dropbox"
import fetch from "isomorphic-fetch"
const apiRoute = nextConnect({
onError(error, req, res) {
res.status(501).json({
error: `Sorry something Happened! ${error.message}`,
})
},
onNoMatch(req, res) {
res.status(405).json({ error: `Method '${req.method}' Not Allowed` })
},
})
const dbx = new Dropbox({
accessToken: process.env.DROPBOX_ACCESS_TOKEN,
fetch,
})
const storage = multerDbx(dbx, {
path: (req, file, cb) => cb(null, "/" + file.originalname),
})
apiRoute.use(multer({ storage }).array("file"))
apiRoute.post((req, res) => {
res.status(200).json({ data: "success" })
})
export default apiRoute
export const config = {
api: {
bodyParser: false,
},
}
These snippets reflect the packages and conventions used by the original project. Treat them as a historical reference rather than a recommendation for a current production upload architecture.