- var express = require('express');
- var app = express();
- var path = require('path');
- var fs = require('fs');
- var url = require('url');
- //指定上传目录,防止权限出错
- app.use(express.bodyParser({uploadDir:'./'}));
- //解析静态文件
- app.all('/*.(html|CSS|js|jpg|png|swf){1}', function(req, res, next){
- //var static_file_formats = ['.html','.css','.js','.jpg','.png'];
- //console.log(path.extname(req.url));
- var realpath = __dirname + '/static' + url.parse(req.url).pathname;
- //console.log(realpath);
- if(path.existsSync(realpath)){
- res.end(fs.readFileSync(realpath));
- }else{
- res.end('Cannot find request url: '+req.url);
- }
- });
- app.post('/upload', function(req, res) {
- // 获得文件的临时路径
- var tmp_path = req.files.Filedata.path;
- var _date=new Date();
- var floder= './';
- var datedir=_date.getFullYear();
- var mm=_date.getMonth()+1;
- if(mm<10){
- datedir+="0"+mm;
- }else{
- datedir+=mm.toString();
- }
- floder+=datedir;
- // 指定文件上传后的目录 - 示例为"images"目录。
- if (!fs.existsSync(floder)) {
- fs.mkdirSync(floder);
- }
- var target_path = floder + '/' + req.files.Filedata.name;
- // 移动文件
- fs.rename(tmp_path, target_path, function(err) {
- if (err) throw err;
- // 删除临时文件夹文件,
- fs.unlink(tmp_path, function() {
- if (err) throw err;
- //返回文件上传后的访问地址
- res.send('http://localhost/uploads/'+datedir+'/'+req.files.Filedata.name);
- //res.send('File uploaded to: ' + target_path + ' - ' +req.files.Filedata.size + ' bytes');
- });
- });
- });
- app.listen(8188);
- //该片段来自于http://www.codesnippet.cn/detail/070320148904.html
来源: http://www.codesnippet.cn/detail/070320148904.html