Kedar Karki
Kedar Karki

Reputation: 538

multer single upload doesnot work but array works

I am using react js to upload a single file. But multer.single() doesnot work whereas multer.array() works. What's the problem?

//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

The error when using single method is

(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.

Client side code is

<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();
    };

What am I doing wrong here?

Upvotes: 2

Views: 884

Answers (2)

sarathlal
sarathlal

Reputation: 1

use both like a middleware in router

const uploadFiles = multer({'./images}).single("profile"); const uploadtext = multer().array()

Upvotes: 0

Maxim Orlov
Maxim Orlov

Reputation: 2582

Main difference between handling single vs multiple file uploads with multer is where the files are located:

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

You can't swap from multiple to single without also accounting for this change further down in your code.

Judging from your error message, in convert.js file (at line 9 column 44) you're failing to read the first element of an array req.files. That's because req.files doesn't exist and you should work with req.file instead which is an object.

This free guide for Parsing Requests in Node.js will help you fix these types of errors when working with file uploads in Node.js.

Upvotes: 2

Related Questions