nodejs版本 v0.10.15,用createReadStream始终没法下载文件,求解决方案
发布于 11 年前 作者 jin123456bat 6816 次浏览 最后一次编辑是 8 年前

尝试过各种办法,百度都翻了好几篇了。,还是没解决 代码如下。

filePath = “D:/web/4.jpg”; function readFile(filePath,response) { filePath = path.join(filePath);

var ContentType;
if(filePath.lastIndexOf(".") == -1)
	throw new Error("Directory is not support download!");
var fileType = filePath.substring(filePath.lastIndexOf(".")+1);//文件类型
ContentType = config.MIME_TYPES[fileType]||"application/octet-stream";
fs.exists(filePath,function(exists){
	if (exists) {
		var rOption = {
			flags : 'r',
			encoding : null,
			fd: null,
			mode : 0666,
			autoClose: true
		}
		if(config.DEBUG)
			console.log("["+core.time()+"] GET files:"+filePath);
		var ReadStream = fs.createReadStream(filePath,rOption);
		ReadStream.on('data',function(data){
			response.write(data);
		});
  //ReadStream.on("data",function(data)
  //{
    //response.write(data);
  //});
		ReadStream.on("error", function() {
			if(config.DEBUG)
				console.log("["+core.time()+"] read files:"+filePath+" has an error!");
			response.writeHead(404,{"Content-Type": "text/plain"}); 
			response.end();
		});
		response.writeHead(200, {"Content-Type": ContentType});
		ReadStream.pipe(response);
		//response.write(filePath);
		ReadStream.on("end", function() {
			//数据发送完毕
			if(config.DEBUG)
				console.log("["+core.time()+"] read files:"+filePath+" success!");
			response.end();
		});
	}else{
		if(config.DEBUG)
			console.log("["+core.time()+"] files:"+filePath+" not exist!");
		response.writeHead(404,{"Content-Type": "text/plain"});
		response.end();
	}
});

}

假如按上面那种方式,浏览器一片空白。没有任何图片下载或显示 假如将ReadStream.pipe(response);注释掉 将//ReadStream.on(“data”,function(data) //{ //response.write(data); //}); 解除注释,可以触发end方法。 我确定文件存在的。 因为console.log("["+core.time()+"] GET files:"+filePath);这句可以在cmd中显示出来 response.write(data);始终返回的null 是不是这个版本的api有问题阿。为什么一直都不行呢?还是说有其他的问题?

2 回复
  res.setHeader('Content-Disposition', 'attachment; filename="h5conf.csv"');
  res.setHeader('Content-Type', 'text/csv; charset=utf-8');
  res.end(result);
回到顶部