Created
December 29, 2023 00:32
-
-
Save bogordesaincom/31c6ad56d590e8d52edbd47a1127c623 to your computer and use it in GitHub Desktop.
Hono Sample Upload using Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Hono } from "hono"; | |
import { indexUser, storeUser } from "../handler/UserHandler"; | |
import uploadFile from "../lib/uploadFile"; | |
const userRouter = new Hono(); | |
userRouter.get("/", indexUser); | |
userRouter.use(uploadFile).post("/", storeUser); | |
export default userRouter; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import path from "path"; | |
import { createWriteStream } from "fs"; | |
import { fileTypeFromBuffer } from "file-type"; | |
const uploadFile = async (c, next) => { | |
const { image } = await c.req.parseBody(); | |
const file = await image.arrayBuffer(); | |
const buffer = Buffer.from(file); | |
const fileType = await fileTypeFromBuffer(buffer); | |
if (fileType.ext) { | |
const outputFileName = path.join( | |
"./public", | |
`${image.name}.${fileType.ext}` | |
); | |
createWriteStream(outputFileName).write(buffer); | |
// c.set("message", "Hono is cool!!"); | |
c.set("file", outputFileName); | |
await next(); | |
} else { | |
await next(); | |
} | |
}; | |
export default uploadFile; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import upload from "../lib/upload"; | |
// const UPLOADS_DIR = "./public"; | |
// const indexUser = async (c) => { | |
// return c.json({ message: "User Index" }); | |
// }; | |
const storeUser = async (c) => { | |
const body = await c.req.parseBody(); | |
console.log(c.get("file")); | |
return c.json({ message: "User Store" }); | |
}; | |
export { indexUser, storeUser }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment