實時開發框架Meteor 實際應用系列---文件的上傳和下載[補充]

接這篇博客。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/@[email protected]".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/@[email protected]".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中間件,使得無法文件流通過異步讀取調用來完成文件下載,我會持續關注這個問題。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章