实时开发框架Meteor 实际应用系列<一>---文件的上传和下载[补充]

11 篇文章 6 订阅
10 篇文章 0 订阅

接这篇博客。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中间件,使得无法文件流通过异步读取调用来完成文件下载,我会持续关注这个问题。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值