文件上传服务器端接收的文件列表中文件名不支持中文,都是乱码,查询发现nodejs对中文支持的不好。
找了半天,发现这个解决方法确实有效!!!!!核心代码
// 解决中文名乱码的问题 file.originalname = Buffer.from(file.originalname, "latin1").toString( "utf8" );
上传时前端正常,但是后端接收文件时乱码
const uploads = multer({ // 文件上传的位置 dest: path.join(__dirname, "../../public/uploads"), fileFilter(req, file, callback) { // 解决中文名乱码的问题 file.originalname = Buffer.from(file.originalname, "latin1").toString( "utf8" ); callback(null, true); }, }); app.post("/upload", uploads.array("files"), async function (req, res) { // 你的代码 })
上我的代码
// 文件上传 const express = require('express'); const router = express.Router(); const multer = require('multer'); const path = require('path') var fs = require('fs'); let createFolder = function(folder){ try{ fs.accessSync(folder); }catch(e){ fs.mkdirSync(folder); } }; let upload = multer({ storage: multer.diskStorage({ //设置文件存储位置 destination: function(req, file, cb) { let date = new Date(); let year = date.getFullYear(); let month = (date.getMonth() + 1).toString().padStart(2, '0'); let day = date.getDate(); let dir = "./uploads/" + year + month + day; //判断目录是否存在,没有则创建 if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } //dir就是上传文件存放的目录 cb(null, dir); }, //设置文件名称 filename: function(req, file, cb) { // const fileFormat = (file.originalname).split('.') // 取后缀 // let fileName = file.fieldname + '-' + Date.now() + ext; // 解决中文名乱码的问题 file.originalname = Buffer.from(file.originalname, "latin1").toString( "utf8" ); let fileName = file.originalname // 判断文件是否存在 fs.access(fileName, error => { if (!error) { // The check succeeded //fileName就是上传文件的文件名 cb(null, fileName); } else { // The check failed let ext = path.extname(file.originalname); let basename = path.basename(file.originalname) let str = basename.split("."); // 以‘.’分割; fileName = str[0] + '-' + Date.now() + ext; //fileName就是上传文件的文件名 cb(null, fileName); } }); } }) }); //多个文件上传 router.post('/upload', upload.array('multerFile'), (req, res) => { console.log(req.files); let fileList = []; req.files.map((elem) => { fileList.push({ originalname: elem.originalname }) }); res.json({ code: 20000, type: 'multer', fileList: fileList }); });
标签:express,fileName,乱码,let,multer,file,originalname From: https://www.cnblogs.com/mazhenyu/p/17014061.html