从azure blob nodejs下载文件

时间:2020-09-17 07:51:33

标签: node.js azure blob

我已经实现了从Blob downloadToFile() not downloading large files Nodejs这样的blob下载文件。并且工作正常。但是问题是 azure->我们的服务器->用户的下载流程,但是我想要的是 azure-> user 的下载流程。请查看上方的链接,并帮助我更改下载流程。

1 个答案:

答案 0 :(得分:0)

更新

我最新更新的答案描述了从后端发送到前端处理的文件流的处理。请谷歌自己将文件转换为流。让我回答您上次提出的问题。

首先,请查看效果图:

enter image description here

服务器代码:

const express=require('express');
const app=express();
const fs = require('fs');
const path =require('path');
const mineType = require('mime-types')

app.listen(7001,()=>console.log('server start'));

app.get('/',(req,res)=>{
    let filePath = path.resolve('mygif.gif');  // local file in project
    let data = fs.readFileSync(filePath);
    let bufferData = new Buffer(data,'base64'); 
    let base64 = 'data:' + mineType.lookup(filePath) + ';base64,' + data; 
    res.send(base64)
})

app.get('/filedownload',function(req, res, next){
    //solve cros issue
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-type');
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
    res.header('Access-Control-Max-Age',1728000);
    // file info 
    var currDir = path.join(__dirname,req.query.dir),
        fileName = req.query.name,
        currFile = path.join(currDir,fileName),
        stats = fs.statSync(currFile);
    fs.exists(currFile,function(exist) {
        if(exist){
            res.set({
                "Content-type":"application/octet-stream",
                "Content-Disposition":"attachment;filename="+encodeURI(fileName),
                'Content-Length': stats.size
            });
            let fReadStream = fs.createReadStream(currFile);
            fReadStream.pipe(res);
        }else{
            res.set("Content-type","text/html");
            res.send("file not exist!");
            res.end();
        }
    });
});

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
    <script>
        function aa(){
            var xhr = new XMLHttpRequest();    
            xhr.open("get", 'http://localhost:7001/filedownload?dir=&name=mygif.gif', true);
            xhr.responseType = "blob";
            xhr.onload = function() {
            if (this.status == 200) {
                var blob = this.response;
                console.log(blob);
            }};
            xhr.send();
        }
        function bb(){
            var oReq = new XMLHttpRequest();
            oReq.open("GET", "http://localhost:7001/filedownload?dir=&name=mygif.gif", true);
            oReq.responseType = "blob";
            oReq.onload = function (oEvent) {
            var content = oReq.response;

            var elink = document.createElement('a');
            elink.download = 'mygif.gif';
            elink.style.display = 'none';

            var blob = new Blob([content]);
            elink.href = URL.createObjectURL(blob);

            document.body.appendChild(elink);
            elink.click();

            document.body.removeChild(elink);
        };
        oReq.send();
    }
</script>
</head>
<body>
    <button onclick="aa()">convert file stream</button>
    <button onclick="bb()">download</button>
</body>
</html>

重要

下载行为必须是浏览器的响应。无论您的节点后端代码如何编码,都将下载到服务器。

要下载到浏览器客户端,最简单的方法是执行window.open(downloadurl)

最友好的方法是生成一个后端,以返回类似于<a href="data:text/plain,this is some text" download="some-filename.txt" target="_blank">Download<a>的消息。消息提示用户下载。

请注意,如果文件太大,则会降低下载速度,请参阅另一篇文章中的答案。

Improve axios get download speed