next上传文件报错?
前端文件: /src/app/api/compress/route.ts
"use client";
import { useState } from "react";
export default function UploadForm() {
const [file, setFile] = useState<File>();
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
// 阻止表单提交行为
e.preventDefault();
if (!file) return;
try {
const data = new FormData();
data.set("file", file);
const res = await fetch("/api/upload", {
method: "POST",
body: data,
}); // handle the error
if (!res.ok) throw new Error(await res.text());
} catch (e: any) {
// Handle errors here
console.error(e);
}
};
return (
<form onSubmit={onSubmit}>
<input type="file" name="file" onChange={(e) => setFile(e.target.files?.[0])} />
<input type="submit" value="Upload" />
</form>
);
}
后端文件:src/app/api/upload/route.ts
import { writeFile } from "fs/promises";
import { NextRequest, NextResponse } from "next/server";
export async function POST(request: NextRequest) {
const data = await request.formData();
const file: File | null = data.get("file") as unknown as File;
if (!file) {
return NextResponse.json({ success: false });
}
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes); // 这里是你要进行保存的文件目录地址
const path = `/tmp/${file.name}`;
await writeFile(path, buffer);
console.log(`open ${path} to see the uploaded file`);
return NextResponse.json({ success: true });
}
报错内容:
麻烦各位熟悉Next的大佬看一下
问题代码的GitHub地址:https://github.com/AnsonZnl/next-upload
回复
1个回答
test
2024-06-24
nextjs 配置有问题,不应该设置为 静态导出,报错那里也指明了。
也可以参考官方文档的解释:https://nextjs.org/docs/pages/building-your-application/deplo...
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容