Node.js Express 从入门到菜鸟(四)——上传图片
express 简单的图片上传并md5加密例子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html> <head> <title></title> </head> <script type="text/javascript" src="/js/jquery.js"></script> <script type='text/javascript'> $(function(){ $("#btnupload").click(function(){ //控制上传文件类型,只能上传jpg var filename=$("#file")[0].value; var ext=filename.split('.')[1]; if(!ext) return false; if(ext=="jpg") { alert("ok"); } else { alert(ext); } return false; }); }); </script> <body> <form enctype="multipart/form-data" action='/processuploadfile' method="post"> <input type='file' name='file' id="file"/> <input type='submit' value='upload' id="btnupload"/> </form>
在app.js文件的app.use(express.bodyParser())替换为此段代码
app.use(express.bodyParser({uploadDir:'./public/upload'}));
设置上传文件的临时文件夹
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
exports.processuploadfile=function(req,res){ var crypto = require('crypto');//node加密模块,支持md5,sha1等加密操作 var path=require("path");//node 路径模块 var fs = require('fs');//node 文件模块 var filename = path.resolve("./"+req.files.file.path);//获得上传文件路径 var md5 = crypto.createHash('md5'); var s = fs.ReadStream(filename); s.on('data', function(d) { md5.update(d); }); s.on('end', function() { var d = md5.digest('hex'); //console.log(d + ' ' + filename); fs.rename(filename,"public/upload/"+d+".jpg", function (err) { if (err) throw err; console.log(d); res.send("ok"); }) }); }