Skip to content

Instantly share code, notes, and snippets.

@Adophilus
Forked from bogordesaincom/UseHandler.js
Created January 28, 2024 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Adophilus/e4d876b550ee8158115aa2681fdd6aea to your computer and use it in GitHub Desktop.
Save Adophilus/e4d876b550ee8158115aa2681fdd6aea to your computer and use it in GitHub Desktop.
Hono Sample Upload using Middleware
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;
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;
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