文件下载在 Nodejs 中提供损坏的文件 [英] File download giving corrupt file in Nodejs

查看:45
本文介绍了文件下载在 Nodejs 中提供损坏的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 NodeJS 中使用请求模块从 AWS S3 读取数据.当我使用下面的代码下载文件(docx 或图像或 pdf)时,它给了我一个无效/损坏的文件.但是当我下载 .txt 文件时,它没有被损坏,我可以在记事本中看到文件.

I am using request module in NodeJS to read data from AWS S3. When I am downloading the file(docx or image or pdf) using below code,its giving me an invalid/corrupted file. But when I am downloading .txt file it's not getting corrupted and I am able to see file in notepad.

我进行了一些谷歌搜索,并按照建议尝试将编码设置为二进制,但仍然没有给出所需的结果.

I did a bit of googling and as suggested also tried by setting encoding to binary, still its not giving required result.

文件上传工作正常.我可以在 AWS 控制台中看到上传的文件.

File upload is working fine. And I am able to see the uploaded file in AWS console.

文件下载代码

var s3 = new properties.AWS.S3();
    var params = {Bucket: properties.AWS_BUCKET, Key: req.headers['x-org'] + "/" + "talk" + "/" + req.body.fileName};
    s3.getSignedUrl('getObject', params, function (err, URL) {
        if (err) {
            console.log("Error inside the S3");
            console.log(err, err.stack); // an error occurred
            res.send(null);
        } else {
            console.log("After getObject:-" + URL);
            request({
                url: URL, //URL to hit
                method: 'GET',
                encoding: 'binary'
            }, function (error, response, body) {
                if (error) {
                    console.log(error);
                } else {
                    //console.log(response.statusCode, body);
                    res.set('content-disposition', 'attachment; filename=' + req.body.fileName);
                    res.send(body);
                }
            });
        }
    });

更新:-我缩小了错误范围,只是尝试通过从本地文件系统读取文件来发送文件.即便如此,也会在客户端上提供损坏的文件.这是相同的代码

Update:- I have narrow down the error, and just trying to send the file by reading file from local file system. Even that also is giving the corrupted files on client. Here's the code for same

var filePath = path.join(__dirname, '..', '..', '..', 'downloads', req.body.fileURL);
    var stat = fs.statSync(filePath);
    var filename = path.basename(filePath);
    var mimetype = mime.lookup(filePath);
    console.log("mimetype=" + mimetype);

    res.setHeader('Content-disposition', 'attachment; filename=' + filename);
    res.setHeader('Content-type', mimetype + ";charset=UTF-8");
    res.setHeader('Content-Length', stat.size);
    var filestream = fs.createReadStream(filePath);
    filestream.pipe(res);

推荐答案

终于可以解决问题了.

从这个博客中得到解决方案的提示 https://templth.wordpress.com/2014/11/21/handle-downloads-with-angular/.

Got solution hint from this blog https://templth.wordpress.com/2014/11/21/handle-downloads-with-angular/.

每个博客

在使用二进制内容(如 zip 文件或图像)进行测试时,我们看到下载的内容已损坏.这是因为Angular 会自动对接收到的数据应用转换.在处理二进制内容时,我们希望将它们作为数组缓冲区.

When testing with binary content like zip files or images, we see that the downloaded content is corrupted. This is due to the fact that Angular automatically applies transformation on the received data. When handling binary contents, we want to get them as array buffer.

最终的工作代码是:-

var filePath = path.join(__dirname, '..', '..', '..', 'downloads', req.body.fileURL);
    var file = fs.createWriteStream(filePath);
    s3.getObject(params).
    on('httpData', function(chunk) { 
        //console.log("inside httpData");
        file.write(chunk); 
    }).
    on('httpDone', function() { 
        console.log("inside httpDone");
        file.end(); 
        //file.pipe(res);
    }).
    send(function() { 
        console.log("inside send");
        res.setHeader('Content-disposition', 'attachment; filename=' + filePath);
        res.setHeader('Content-type', mimetype);
        res.setHeader('Transfer-Encoding', 'chunked');
        var filestream = fs.createReadStream(filePath);
        filestream.pipe(res);
    });

这篇关于文件下载在 Nodejs 中提供损坏的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆