我是 elysiajs 新手,尝试使用 multer 和 elysia 上传文件,但它对我不起作用 我尝试添加前手柄和后手柄,但它仍然不起作用, ...................................................... ........................
const storage = multer.diskStorage({
destination: "./uploads/",
filename: function (req, file, cb) {
cb(
null,
file.fieldname + "-" + Date.now() + path.extname(file.originalname)
);
},
});
const upload = multer({
storage: storage,
limits: { fileSize: 1000000 }, // Limit file size to 1MB
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
},
}).single("myFile"); // 'myFile' is the name of the file input field in the HTML form
// Check file type
function checkFileType(file: any, cb: any) {
// Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb("Error: Images Only!");
}
}
export const users = new Elysia({ prefix: "/files" })
// .post("/s", upload);
.guard(
{
beforeHandle() {
upload;
},
},
(users) =>
users
.post("/s", (req: any, res: any) => filesUpload(req, res))
.get("/ss", () => "f")
);
帮我回答一下,实际上当你使用 Elysiajs 和 Bun 时。 Bun 有一个内置功能可以上传文件,无需使用 multer 等外部插件。
对于路线中的示例,您可以像这样实现它可以处理您,
app.post(
"/",
async ({
body,
}: {
body: {
logo: File;
fileVerification: File;
data: string;
};
}) => {
return RegisteredVillageController.addVillages({ body });
},
{
tags: ["Registered_Village"],
body: t.Object({
logo: t.File({ description: "logo" }),
fileVerification: t.File({ description: "fileVerification" }),
data: t.String(),
}),
type: "formdata",
required: ["file", "fileVerification", "data"],
}
);
然后在控制器内,您可以添加
Bun.write
将文件写入面包内。在此示例中,为了命名文件,我使用了 nanoid,您可以先安装它。
addVillages: async ({
body,
}: {
body: {
logo: File;
fileVerification: File;
data: string;
};
}) => {
try {
const file = body.logo;
const fileVerification = body.fileVerification;
const data = JSON.parse(body.data) as PropsVillage;
if (!file.type.includes("image")) {
return {
data: [],
message: "Unsupported Format File",
};
}
if (!fileVerification.type.includes("pdf")) {
return {
data: [],
message: "Unsupported Format File Verification",
};
}
// file
const ext = file.type === "image/jpeg" ? ".jpg" : ".png";
const baseDir = "files/logo/";
const newFileName = `${baseDir}${nanoid.nanoid()}${ext}`;
await Bun.write(newFileName, file);
const baseDirPdf = "files/pdf/";
const newPdfName = `${baseDirPdf}${nanoid.nanoid()}.pdf`;
await Bun.write(newPdfName, file);
} catch (error: any) {
console.log("🚀 ~ addVillages: ~ error:", error);
return {
data: [],
message: error.message,
};
}
},