【问题帖】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...

相关推荐
java硕哥14 小时前
Spring源码debug方法
java·后端·spring
@菜菜_达14 小时前
前端 HTML 入门(标签)
前端·html
智航GIS14 小时前
7.1 自定义函数
前端·javascript·python
BlackWolfSky14 小时前
React中文网课程笔记1—快速入门
前端·笔记·react.js
A_one201014 小时前
利用npm内置命令构建脚本工具
前端·npm·node.js
刘立军14 小时前
本地大模型编程实战(39)MCP实战演练
人工智能·后端·mcp
JH307314 小时前
Spring Retry 实战:优雅搞定重试需求
java·后端·spring
ZoeGranger14 小时前
【Spring】使用注解开发
后端
哔哩哔哩技术14 小时前
2025年哔哩哔哩技术精选技术干货
前端·后端·架构
霍理迪14 小时前
CSS布局方式——定位
前端·css