我想在下一个具有强大模块的应用程序中将图像上传到公共文件夹,但我遇到了一些错误。报错信息是这样的:
error - TypeError: req.on is not a function at IncomingForm.parse (webpack-internal:///(sc_server)/./node_modules/formidable/src/Formidable.js:182:13) at readFile (webpack-internal:///(sc_server)/./app/api/route.js:42:10) at POST (webpack-internal:///(sc_server)/./app/api/route.js:52:11)
我遵循了一些 youtube 教程,但它不是 nextJS 13,也许这就是问题所在,我也将 formidable 更新到 v3,但没有帮助。
这是前端页面代码,用户可以在其中将图像上传到公共文件夹:
'use client';
import { useState } from 'react';
import Image from 'next/image';
import axios from 'axios';
export default function Home() {
const [selectedFile, setSelectedFile] = useState('');
const [selectedImage, setSelectedImage] = useState('');
const submitHandler = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('image', selectedFile);
const res = await axios.post('/api', formData);
console.log(res);
};
return (
<div className=''>
<form>
<label>
<input
type='file'
hidden
onChange={({ target }) => {
if (target.files) {
const file = target.files[0];
setSelectedImage(URL.createObjectURL(file));
setSelectedFile(file);
}
}}
/>
<div className='w-40 aspect-video rounded flex items-center justify-center border-2 border-dashed cursor-pointer'>
{selectedImage ? <img src={selectedImage} alt='' /> : <span>Select Image</span>}
</div>
</label>
<input type='submit' value='Submit' onClick={submitHandler} />
</form>
</div>
);
}
这里是后端代码,api路由,我发送post请求的地方:
import { NextResponse } from 'next/server';
import formidable from 'formidable';
import path from 'path';
import fs from 'fs/promises';
export const config = {
api: {
bodyParser: false,
},
};
const readFile = async (req, saveLocally) => {
const options = {};
if (saveLocally) {
options.multiple = true;
options.uploadDir = path.join(process.cwd(), '/public/images');
options.filename = (name, ext, path, form) => {
return Date.now().toString() + '_' + path.originalFilename;
};
}
options.maxFileSize = 4000 * 1024 * 1024;
const form = formidable(options);
form.parse(req, (err, fields, files) => {
if (err) console.log('error');
});
};
export async function POST(req, res) {
try {
await fs.readdir(path.join(process.cwd() + '/public', '/images'));
} catch (error) {
await fs.mkdir(path.join(process.cwd() + '/public', '/images'));
}
await readFile(req, true);
res.json({ done: 'ok' });
}
res.json({ done: 'ok' });
发生在 form.parse 回调之前。 承诺并等待它