node 实现上传 和 下载 文件接口 简易版
作者:互联网
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;
标签:node,fs,res,req,简易版,file,var,path,上传 来源: https://www.cnblogs.com/jackie-song/p/15843025.html