nodejs版本 v0.10.15,用createReadStream始终没法下载文件,求…
nodejs吧
全部回复
仅看楼主
level 12
jin123456bat 楼主
尝试过各种办法,百度都翻了好几篇了。,还是没解决代码如下。
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有问题阿。为什么一直都不行呢?还是说有其他的问题?
2013年07月31日 10点07分 1
1