expressjs / expressjs/multer

Output size 0 when reading the stream

Open
#949 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
12.1k
Forks
1.1k
Avg merge
8d 2h
Merged PRs (30d)
21

Description

Hi!

I have found a comment here https://github.com/expressjs/multer/issues/713#issuecomment-458664698 which shows how to read file stream as a buffer, so I did. However, after reading the stream, the size of the output file was 0, and the content of the file was empty.

Is it suppose to happen?

Here is my code:
```jsx
import { Router } from "express";
import * as getStream from "get-stream";
import { Magic, MAGIC_MIME } from "mmmagic";
import * as mime from "mime-types";

const slug = require("speakingurl");

const magic = new Magic(MAGIC_MIME);

const upload = multer({
storage: multer.diskStorage({
async filename(_, file, next) {
const buffer = await getStream.buffer(file.stream); // This line itself causing the problem

magic.detect(buffer, (err, result) => {
let [mimeType] = result;

if (typeof result === "string") mimeType = result;

const extension = mime.extension(mimeType) || "";
const fileName = file.originalname.replace(`.${extension}`, "");

const slugFilename = slug(fileName, {
truncate: 40,
maintainCase: true,
separator: "_",
});

const newFilename = `${Date.now()}-${slugFilename}.${extension}`;

next(err, newFilename);
});
},
destination: `${PUBLIC_IMAGE_FOLDER}/`,
}),
limits: {
fileSize: 2 * 5 * 1024 * 1024,
},
});

const router = Router();

router.post("/", upload.single("file"), async (req, res) => {
res.json({
success: true,
});
});
```

```
"express": "^4.17.1",
"get-stream": "^6.0.0",
"mmmagic": "^0.5.3",
"multer": "^1.4.2",
"speakingurl": "^14.0.1",
```

I'm using `mmmagic` to read the file's mime-type. The client might post a file with an incorrect file extension and I have confirmed that Mulder's `file.mimetype` prop is based on the file extension. So to avoid this, getting mime-type from Buffer is needed.

Contributor guide

Open the contributing guide

Research direction

Start at the multer diskStorage filename callback shown in the issue, especially where get-stream.buffer(file.stream) consumes the stream before the destination writes it. Reproduce the upload with the supplied Express route and dependencies, then determine whether the stream lifecycle is supported; done means the behavior is explained and a documented or tested resolution is identified.

Written by the indexing model from the issue text.

Assessment

Tech stack
express, javascript, node.js
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.