关于文件查看和下载
发布于 8 年前 作者 im-here 3788 次浏览 来自 问答

需求是这样的:我想用nodejs搭一个静态文件服务器(假定为A服务器),供其他服务器使用。我现在要在A服务器上实现2个api,一个为文件查看,一个为文件下载。查看api是查看文件内容,就好比我的A服务器上放了一些今天文本文件,通过这个api可以直接查看该文件里的内容。下载api就是直接下载文件了。我现在已经在A服务器上实现了两个api。分别为: 文件查看:www.a.com/lookup?name=xxx, 文件下载:www.a.com/download?name=xxx 我现在直接通过访问A服务器上面两个链接,是可以实现文件查看和下载的。但是我实际想要的效果是:A服务器存放静态文件并提供api,然后别的服务器通过代码构造get请求,访问上面的两个链接实现查看和下载效果。我现在文件查看已经实现了,但是下载有问题。 A服务器代码:

//文件查看:
function lookup(path,response) {
    var data = '';
    fs.exists(path, function (exists) {        
        var content = fs.createReadStream(path, { flags: 'r' });
        response.writeHead(200, {
            'Content-Type': 'application/json;charset=utf-8'
        });
        content.on('data', function (trunk) {
            data += trunk;
        });
        content.on('end', function () {           
            response.write(data);
            response.end();
        });
    });

}
//文件下载:
function download(path,filename,response) {        
    fs.exists(path, function (exists) {       
        fs.stat(path, function (err,stats) {            
            var content = fs.createReadStream(path, { flags: 'r' });        
            response.writeHead(200, {
                'Content-Type': 'text/plain',
                "Content-Length": stats.size,
                'Content-Disposition': 'attachment; filename=' + filename
            });
            content.pipe(response);
            content.on('end', function () {
                response.end();
            });
        });
    });
}

别的服务器访问A服务器上的api

文件查看:
Test.lookup = function (req, res) { 
 var  http = require('http'), 
    content='name=test.txt';
    var options = {
        hostname: 'www.a.com',
        port: 80,
        path:'/lookup?'+content,  
        method: 'GET'
    };
    var _req = http.request(options, function (result) {
         res.writeHead(200, {'Content-Type': 'application/json;charset=utf-8'});           
        result.on('data', function (chunk) {
            console.log(chunk);
            res.write(chunk);
            res.end();
        });  
    });
  _req.end();
};

现在就剩文件下载没搞定了,应该怎么弄呢?

3 回复

你可以参考一下MIME-TYPE的官方定义,把下载的那个Content-Type换成 application/octet-stream 试试

下载看下 Content-Disposition 头

a 标签的 download 属性

回到顶部