【问题帖】Next上传文件报错,求大佬看一下

前端文件: /src/app/api/compress/route.ts

tsx 复制代码
"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

tsx 复制代码
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地址:github.com/AnsonZnl/ne...

相关推荐
LucianaiB43 分钟前
干货 | 手把手教你用 OpenClaw + Skill 实现微信公众号全自动创作发布
后端
eggwyw1 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
韩立学长1 小时前
Springboot奶茶加盟信息管理系统m307m786(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
小小小小宇1 小时前
软键盘常见问题(二)
前端
小小小小宇2 小时前
软键盘常见问题
前端
开longlong了吗?2 小时前
Luan Takeaway——大模型驱动的智能外卖管理系统( Spring Cloud、Langchain4j )
后端·spring·spring cloud·langchain
小小小小宇2 小时前
富文本编辑器知识体系(三)
前端
小小小小宇2 小时前
富文本编辑器知识体系(二)
前端
品克缤2 小时前
Trading-Analysis:基于“规则+LLM”的行情分析终端(兼谈 Vibe Coding 实战感)
前端·后端·node.js·vue·express·ai编程·llama
隔壁小邓2 小时前
前端Vue项目打包部署实战教程
前端·javascript·vue.js