javascript - multer 单个上传不起作用,但数组可以工作

标签 javascript node.js reactjs multer

我正在使用 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();
    };

我在这里做错了什么?

最佳答案

使用 multer 处理单个文件上传与多个文件上传之间的主要区别在于文件所在的位置:

  • upload.single() -> req.file
  • upload.array()(和upload.fields())-> req.files

如果不在代码中进一步考虑此更改,则无法从多个交换为单个。

从错误消息来看,在 convert.js 文件(第 9 行第 44 列)中,您无法读取数组的第一个元素 req.files 。这是因为 req.files 不存在,您应该使用 req.file 而不是它,它是一个对象。

此免费指南 Parsing Requests in Node.js将帮助您在 Node.js 中处理文件上传时修复这些类型的错误。

关于javascript - multer 单个上传不起作用,但数组可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67866579/

相关文章:

javascript - Jquery 中的 CSS 位置和 if 语句

javascript - ReactJS:渲染组件时触发方法

macos - 如何重新启动 node.js 服务器

Javascript 导入句柄未定义

node.js - Redux-Thunk "Actions must be plain objects. Use custom middleware for async actions."

javascript - 如何将 React Hooks 与 video.js 一起使用?

javascript - React 在 setState 中访问超出范围的变量

javascript - 使用gmaps使用css在div下方创建箭头

javascript - 未捕获的 TypeError : Failed to execute 'insertRule' on 'CSSStyleSheet' : 2 arguments required, 但只有 1 个存在

javascript - 在屏幕外的文本上使用 javascript 替换