【发布时间】:2021-08-24 05:46:01
【问题描述】:
我正在使用 react js 上传单个文件。但是 multer.single() 不起作用,而 multer.array() 起作用。有什么问题?
//Node.js
const upload = multer({
storage: multer.diskStorage({
destination: './uploads',
filename: (_, file, cb) => cb(null, file.originalname),
}),
});
// app.use(upload.array('pdf')); // works
app.use(upload.single('pdf')); // not working
使用单一方法时的错误是
(node:6096) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
at convertToJPG (D:\Projects\Node\pdf2pic\controllers\convert.js:9:44)
at Layer.handle [as handle_request] (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\layer.js:95:5)
at D:\Projects\Node\pdf2pic\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\index.js:335:12)
at next (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\index.js:275:10)
at Function.handle (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\index.js:174:3)
at router (D:\Projects\Node\pdf2pic\node_modules\express\lib\router\index.js:47:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6096) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6096) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
客户端代码是
<input
accept=".pdf"
multiple={false}
name="pdf"
onChange={onChangeHandler}
ref={fileInputRef}
style={{ display: 'none' }}
type="file"
/>
const onChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
if (!event.target.files?.length) {
return;
}
const formData = new FormData();
Array.from(event.target.files).forEach((file) => {
formData.append(event.target.name, file);
});
props.onChange(formData);
formRef.current?.reset();
};
我在这里做错了什么?
【问题讨论】:
-
D:\Projects\Node\pdf2pic\controllers\convert.js:9:44的代码是什么?您可能正在尝试在那里访问req.files数组,但使用single时没有数组,而只有req.file属性。 (注意files与file的区别)
标签: javascript node.js reactjs multer