当前位置: 首页 > 知识库问答 >
问题:

前端 - next上传文件报错?

宗政燕七
2023-11-16

前端文件: /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 });}

报错内容:
image.png

麻烦各位熟悉Next的大佬看一下

问题代码的GitHub地址:https://github.com/AnsonZnl/next-upload

共有2个答案

彭涵衍
2023-11-16

nextjs 配置有问题,不应该设置为 静态导出,报错那里也指明了。

image.png

也可以参考官方文档的解释:https://nextjs.org/docs/pages/building-your-application/deplo...

方宜
2023-11-16

看起来你在上传文件时遇到了错误。这个错误可能是由于多种原因引起的,比如文件类型不正确、文件大小超过限制、服务器没有写入权限等。然而,根据你提供的代码和错误信息,我认为问题可能在于你尝试从 FormData 中获取文件,但没有正确地处理它。

在你的前端代码中,你尝试从 onChange 事件中获取文件,然后将其存储在状态中。然后,在 onSubmit 函数中,你创建一个新的 FormData 对象,设置文件,然后发送请求。

然而,在你的后端代码中,你试图从 request.formData() 中获取文件。这可能不会按预期工作,因为 request.formData() 可能不会包含你在 FormData 对象中设置的所有数据。

我建议你尝试以下更改:

在你的前端代码中,当你从输入字段中获取文件后,也将其添加到 FormData 对象中:

const onChange = (e) => {  setFile(e.target.files?.[0]);  const data = new FormData();  data.append("file", file);  // You may need to adjust the URL based on your app's structure  fetch("/api/upload", {    method: "POST",    body: data,  });};

在你的后端代码中,从 request.body 中获取文件,而不是 request.formData()

import { getBody } from "next/server";export async function POST(request: NextRequest) {  const data = getBody(request);  const file = data.file; // 'file' is the key you appended to the FormData object in the frontend  if (!file) {    return NextResponse.json({ success: false });  }  // The rest of your code remains the same...}

这应该解决你的问题。如果问题仍然存在,那么可能是其他问题,如文件类型不正确、文件大小超过限制、服务器没有写入权限等。

 类似资料: