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

相关推荐
yuuki2332331 天前
【数据结构】栈
c语言·数据结构·后端
flypwn1 天前
TFCCTF 2025 WebLess题解
服务器·前端·数据库
b***74881 天前
前端CSS预处理器对比,Sass与Less
前端·css·sass
程序猿小蒜1 天前
基于springboot的共享汽车管理系统开发与设计
java·开发语言·spring boot·后端·spring·汽车
lsp程序员0101 天前
使用 Web Workers 提升前端性能:让 JavaScript 不再阻塞 UI
java·前端·javascript·ui
J***Q2921 天前
前端路由,React Router
前端·react.js·前端框架
1***81531 天前
前端路由参数传递,React与Vue实现
前端·vue.js·react.js
q***46521 天前
在2023idea中如何创建SpringBoot
java·spring boot·后端
hygge9991 天前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis