Express + MongoDB + multer 解决文件上传 originalname 中文乱码

出现originalname中文乱码,是因为请求时给后端的是 UTF-8 编码的文件名,而后端 Node.js 在解析文件名时,是以 ISO-8859-1 编码来解析的。

一、手动转换编码

在接收到文件后,对文件名进行编码转换。

1. 单文件

// multer配置
const storage = multer.diskStorage({
    
    
  destination: function (req, file, cb) {
    
    
    cb(null, "uploads/"); // 设置文件存储目录
  },
  filename: function (req, file, cb) {
    
    
    // 这里假设上传了单个文件
    file.originalname = Buffer.from(file.originalname, "latin1").toString(
      "utf-8"
    );
    cb(null, file.originalname);
  },
});
const upload = multer({
    
     storage: storage });
app.post("/upload", upload.single("file"), (req, res) => {
    
    
  // 处理上传后的逻辑,比如将文件信息存入MongoDB
  res.send("文件上传成功");
});

2. 多文件

// multer配置(多文件上传)
const storage = multer.diskStorage({
    
    
  destination: function (req, file, cb) {
    
    
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    
    
    // 遍历处理多个文件
    req.files.forEach((singleFile) => {
    
    
      singleFile.originalname = Buffer.from(
        singleFile.originalname,
        "latin1"
      ).toString("utf-8");
    });
    cb(null, file.originalname);
  },
});

const upload = multer({
    
     storage: storage });

app.post("/upload", upload.array("file", 5), (req, res) => {
    
    
  // 处理上传后的逻辑,比如将文件信息存入MongoDB
  res.send("文件上传成功");
});

二、自定义中间件

创建一个中间件来统一处理文件名乱码问题,这样可以在多个路由中复用。

const fixFileNameEncoding = (req, res, next) => {
    
    
  if (req.files) {
    
    
    if (Array.isArray(req.files)) {
    
    
      req.files.forEach((file) => {
    
    
        file.originalname = Buffer.from(file.originalname, "latin1").toString(
          "utf-8"
        );
      });
    } else {
    
    
      req.files.originalname = Buffer.from(
        req.files.originalname,
        "latin1"
      ).toString("utf-8");
    }
  }
  next();
};
app.post("/upload", upload.single("file"), fixFileNameEncoding, (req, res) => {
    
    
  // 处理上传后的逻辑,比如将文件信息存入MongoDB
  res.send("文件上传成功");
});