Vra*_*nki 6 javascript file-upload next.js
如何在 next.js API 路由中获取上传的图像并将其保存在公共文件夹中?我已经准备好了前端。我正在使用纯 JavaScript 将图像上传到端点。这里是上传图片的onSubmit函数。如果我在这里做错了,请建议我。主要问题是如何检索它?
const onSubmit=async(e)=>{
e.preventDefault();
const fd=new FormData()
fd.append('myfile',image.name)
let res=await fetch(`http://localhost:3000/api/upload`,{
method: 'POST',
headers: {
"Content-Type": "image/jpeg",
},
body: fd,
})
let response=await res.json();
Run Code Online (Sandbox Code Playgroud)
还有一个额外的问题,将上传的图像保存在公共文件夹中肯定不是一个好主意。我已将其保存在云中的某个位置。
小智 16
Nextjs 13+ 完全能够自行处理表单数据和图像上传。您不需要强大的、multer 等...您可以使用以下代码轻松地将图像保存到本地目录。
import { NextResponse } from "next/server";
import path from "path";
import { writeFile } from "fs/promises";
export const POST = async (req, res) => {
const formData = await req.formData();
const file = formData.get("file");
if (!file) {
return NextResponse.json({ error: "No files received." }, { status: 400 });
}
const buffer = Buffer.from(await file.arrayBuffer());
const filename = Date.now() + file.name.replaceAll(" ", "_");
console.log(filename);
try {
await writeFile(
path.join(process.cwd(), "public/uploads/" + filename),
buffer
);
return NextResponse.json({ Message: "Success", status: 201 });
} catch (error) {
console.log("Error occured ", error);
return NextResponse.json({ Message: "Failed", status: 500 });
}
};
Run Code Online (Sandbox Code Playgroud)
这是我在 nextjs 中用于上传图像的端点代码,它需要一些额外的包,我也会在下面列出它们。
import nextConnect from "next-connect";
import multer from "multer";
import { v4 as uuidv4 } from "uuid";
let filename = uuidv4() + "-" + new Date().getTime();
const upload = multer({
storage: multer.diskStorage({
destination: "./public/uploads/profiles", // destination folder
filename: (req, file, cb) => cb(null, getFileName(file)),
}),
});
const getFileName = (file) => {
filename +=
"." +
file.originalname.substring(
file.originalname.lastIndexOf(".") + 1,
file.originalname.length
);
return filename;
};
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` });
},
});
apiRoute.use(upload.array("file")); // attribute name you are sending the file by
apiRoute.post((req, res) => {
res.status(200).json({ data: `/uploads/profiles/${filename}` }); // response
});
export default apiRoute;
export const config = {
api: {
bodyParser: false, // Disallow body parsing, consume as stream
},
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29341 次 |
| 最近记录: |