Skip to content

Commit

Permalink
Fix UTF-8 file name uploads
Browse files Browse the repository at this point in the history
  • Loading branch information
Cohee1207 committed Apr 27, 2024
1 parent cbedfa4 commit 943906d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions server.js
Expand Up @@ -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);
Expand Down
30 changes: 30 additions & 0 deletions src/middleware/multerMonkeyPatch.js
@@ -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;

0 comments on commit 943906d

Please sign in to comment.