var express = require('express');
var fs = require('fs');
var path = require('path');
var multipart = require('connect-multiparty');
var router = express.Router();
router.post('/upload', multipart(), function (req, res) {
//获得文件名
console.log(req.files.file.originalFilename)
var filename = req.files.file.originalFilename;
//复制文件到指定路径
var targetPath = './file/uploads/' + filename;
//复制文件流
fs.createReadStream(req.files.file.path).pipe(fs.createWriteStream(targetPath));
//响应ajax请求,告诉它图片传到哪了
res.json({ code: 200, data: { url: 'http://' + req.headers.host + '/file/uploads/' + filename } });
});
router.get('/download/*', function (req, res, next) {
var name = req.params[0];
var path = './file/uploads/' + name;
var size = fs.statSync(path).size;
var f = fs.createReadStream(path);
res.writeHead(200, {
'Content-Type': 'application/force-download',
'Content-Disposition': 'attachment; filename=' + encodeURIComponent(name),
'Content-Length': size
});
f.pipe(res);
});
module.exports = router;