我正在使用 Next.js 13 开发一个项目,在尝试将图像上传到服务器时遇到问题。我收到的错误消息是:
- error Error: ENOENT: no such file or directory, open 'temp/img.jpeg'
这是我的应用程序的客户端代码:
"use client";
import axios from "axios";
import { useState } from "react";
export default function Home() {
const [file, setFile] = useState();
const [name, setname] = useState("rishabh");
const submit = async (e) => {
e.preventDefault();
const formdata = new FormData();
formdata.set("file", file);
const res = await axios.post("/api/post", formdata);
console.log(res);
};
function sendfile(e) {
console.log(e.target.files[0]);
setFile(e.target.files[0]);
console.log(file);
}
return (
<div>
<form onSubmit={submit}>
<label>upload files</label>
<input
name="file"
onChange={(e) => setFile(e.target.files[0])}
type="file"
></input>
<button type="submit">Submit</button>
</form>
</div>
);
}
这是我的应用程序的服务器端代码:
import { writeFile, writeFileSync } from "fs";
import { NextRequest,NextResponse } from "next/server";
import {join} from 'path';
export async function POST(NextRequest)
{
const data = await NextRequest.formData();
const file = data.get('file');
const bytes = await file.arrayBuffer()
const buffer = Buffer.from(bytes)
const path = join('./','temp',file.name)
console.log('====================================');
console.log(file.name,buffer);
console.log('====================================');
writeFileSync(path,buffer);
return NextResponse.json({message:"get"})
}