node express formidable 文件上传后修改文件名

Posted Yuri 前端什么狮子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了node express formidable 文件上传后修改文件名相关的知识,希望对你有一定的参考价值。

//我是用php的思想来学习nodejs

var
express = require(\'express\'); var router = express.Router(); var fs = require(\'fs\'); var path= require("path"); var formidable = require(\'formidable\'); /* GET home page. */ router.get(\'/\', function(req, res, next) { res.render(\'index\', { title: \'Express+EJS+mysql+s2\' }); }); router.post(\'/file-upload\', function(req, res, next) { console.log(\'开始文件上传....\'); var form = new formidable.IncomingForm(); //设置编辑 form.encoding = \'utf-8\'; //设置文件存储路径 form.uploadDir = "./public/images/"; //保留后缀 form.keepExtensions = true; //设置单文件大小限制 form.maxFieldsSize = 2 * 1024 * 1024; //form.maxFields = 1000; 设置所以文件的大小总和 form.parse(req, function(err, fields, files) { //console.log(fields); console.log(files.thumbnail.path); console.log(\'文件名:\'+files.thumbnail.name); var t = (new Date()).getTime(); //生成随机数 var ran = parseInt(Math.random() * 8999 +10000); //拿到扩展名 var extname = path.extname(files.thumbnail.name); //path.normalize(\'./path//upload/data/../file/./123.jpg\'); 规范格式文件名 var oldpath = path.normalize(files.thumbnail.path); //新的路径 let newfilename=t+ran+extname; var newpath = \'./public/images/\'+newfilename; console.warn(\'oldpath:\'+oldpath+\' newpath:\'+newpath); fs.rename(oldpath,newpath,function(err){ if(err){ console.error("改名失败"+err); } res.render(\'index\', { title: \'文件上传成功:\', imginfo: newfilename }); }); //res.end(util.inspect({fields: fields, files: files})); }); }); /* supervisor ./bin/www */ module.exports = router;
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel=’stylesheet’ href=’/stylesheets/style.css’ />
</head>
<body>
<h5>这里变量没有输出但没有报销:<%= locals.title %></h5>
<p>Welcome to <%= title %></p>

<img src=\'./images/<%= locals.imginfo %>\' width=\'200\'/>


<form method="post" enctype="multipart/form-data" action="/file-upload">
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="file" name="thumbnail">
  <input type="submit">
</form>
</body>
</html>

 

以上是关于node express formidable 文件上传后修改文件名的主要内容,如果未能解决你的问题,请参考以下文章

Node.js的Formidable模块的使用,方便快捷

node学习笔记_04 express相册

使用 express 在 node.js 中获取选定的选项值

node 静态资源服务中间件 错误路由处理中间件 next向下匹配 nodemon热更新 表单数据处理formidable cookie-parser中间件

node16---cookie session

Node实现简单的表单+图片上传+路由