Fix UTF-8 file name uploads

https://github.com/expressjs/multer/issues/1104
This commit is contained in:
Cohee 2024-04-27 22:58:32 +03:00
parent cbedfa4664
commit 943906d8a3
2 changed files with 31 additions and 0 deletions

View File

@ -286,6 +286,7 @@ app.use(userModule.requireLoginMiddleware);
// File uploads
app.use(multer({ dest: UPLOADS_PATH, limits: { fieldSize: 10 * 1024 * 1024 } }).single('avatar'));
app.use(require('./src/middleware/multerMonkeyPatch'));
// User data mount
app.use('/', userModule.router);

View File

@ -0,0 +1,30 @@
/**
* Decodes a file name from Latin1 to UTF-8.
* @param {string} str Input string
* @returns {string} Decoded file name
*/
function decodeFileName(str) {
return Buffer.from(str, 'latin1').toString('utf-8');
}
/**
* Middleware to decode file names from Latin1 to UTF-8.
* See: https://github.com/expressjs/multer/issues/1104
* @param {import('express').Request} req Request
* @param {import('express').Response} _res Response
* @param {import('express').NextFunction} next Next middleware
*/
function multerMonkeyPatch(req, _res, next) {
try{
if (req.file) {
req.file.originalname = decodeFileName(req.file.originalname);
}
next();
} catch (error) {
console.error('Error in multerMonkeyPatch:', error);
next();
}
}
module.exports = multerMonkeyPatch;