接这篇博客。http://blog.csdn.net/a6383277/article/details/23023269
上篇博客的下载部分我将讲的有点简陋,没有涉及到文件流的读取,因此补充如下。[这个解决方案也不完整的,以后出来完整方案我会继续补充]
项目仅需要一个server文件夹下的index.js文件即可。当然也都需要iron-router包
代码如下:
var fs = Npm.require('fs');
/* 暂时无法通过异步回调函数进行 原因:https://github.com/EventedMind/iron-router/issues/300
var displayImag = function(hashCode,response){
//如果文件是存硬盘,hashCode应该避免访问其他资源,或者采取其他非字符串拼接方式
var filePath = "/home/ec/@hashCode@.png".replace('@hashCode@',hashCode.replace(/(\.)+|(\/)/g,""));
fs.exists(filePath,function(exists){
if(!exists){
response.writeHead(404,{"Content-Type":"text/plain"});
response.write("404,请求资源"+uri+"不存在");
response.end();
return;
}
var fileStream = fs.createReadStream(filePath);
response.setHeader("Content-Disposition", "inline;");
response.writeHead(200, {"Content-Type": "image/png"});
fileStream.pipe(response);
fileStream.on('end',function(){
response.end();
})
});
}
*/
Router.map(function() {
this.route('postsShow', {
where: 'server',
path: '/img/:hashCode',
action: function() {
var hashCode = this.params.hashCode;
console.log(hashCode)
//displayImag(hashCode,this.response)
//如果文件是存硬盘,hashCode应该避免访问其他资源,或者采取其他非字符串拼接方式
var filePath = "/home/ec/@hashCode@.png".replace('@hashCode@',hashCode.replace(/(\.)+|(\/)/g,""));
var fileSize = fs.statSync(filePath)
this.response.writeHead(200, {
'Content-Type': 'image/png', // Change to the type of file you're serving
'Content-Disposition': 'inline',
'Content-Size': fileSize
})
this.response.write(fs.readFileSync(filePath))
this.response.end()
}
});
});
由于iron-router使用了Connect中间件,使得无法文件流通过异步读取调用来完成文件下载,我会持续关注这个问题。