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

相关推荐
止观止14 分钟前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall14 分钟前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴20 分钟前
简单入门Python装饰器
前端·python
ai小鬼头1 小时前
AIStarter如何助力用户与创作者?Stable Diffusion一键管理教程!
后端·架构·github
袁煦丞1 小时前
数据库设计神器DrawDB:cpolar内网穿透实验室第595个成功挑战
前端·程序员·远程工作
简佐义的博客1 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
天天扭码1 小时前
从图片到语音:我是如何用两大模型API打造沉浸式英语学习工具的
前端·人工智能·github
Liudef061 小时前
2048小游戏实现
javascript·css·css3
Code blocks2 小时前
使用Jenkins完成springboot项目快速更新
java·运维·spring boot·后端·jenkins