path处理、分割路径方便;
fs可以提供修改文件名操作;
multer是http文件传输中间件;
iconv-lite转换中文编码库(没用上);
字符处理:1、直接扔掉文件名;2、要求前端显式的提供文件名;
const express = require("express");
const multer = require("multer");
const path = require("path");
const fs = require(‘fs‘);
const iconv = require("iconv-lite")
const server = express();
var objMulter = multer({
dest: ‘./files‘
});
server.use(objMulter.any());
server.post(‘/‘, (req, res, next) => {
// var old_filePath = req.files[0].path; //读取已经存储后的路径;
// var new_filename = req.files[0].filename; //读取已经存储后文件名;
// if (req.body.filename) { //选择前端给出了filename
// new_filename = req.body.filename;
// }
// var new_fileName = new_filename + path.parse(req.files[0].originalname).ext;//加后缀
// var new_filePath = req.files[0].destination + "/" + new_fileName;//加钱缀
// //准备改文件名;
// console.log(old_filePath, "==>", new_filePath);
// fs.rename(old_filePath, new_filePath, (err) => {
// if (err) console.log("文件重命名失败");
// });
// urlname = new_filePath;
// console.log(req.files[0]);
// res.send({
// code: 1,
// msg: "success",
// urlname: urlname,
// db_name:new_filename,
// db_type:path.parse(req.files[0].originalname).ext,
// db_size:req.files[0].size,
// })
var fileData=req.files[0];
fileData.ext=path.parse(fileData.originalname).ext;
fileData.id=fileData.filename;
fileData.filename=fileData.id+fileData.ext;
if(req.body.filename){//前端给出了改名建议
new_filepath=fileData.destination+"/"+req.body.filename+fileData.ext;
}else{//没有前端建议也要添加后缀名
new_filepath=fileData.path+fileData.ext;
}
// console.log(fileData.path, "==>", new_filepath);
fs.rename(fileData.path,new_filepath,(err) => {
if (err) console.log("文件重命名失败");
});
fileData.urlname=new_filepath;
res.send(fileData)
})
server.listen(8080);
{{uploading-image-130288.png(uploading...)}}