对烧瓶中的多个文件做出响应

时间:2019-05-07 01:39:59

标签: python flask

使用send_file()send_from_directory()可以对flask中的单个文件对象做出有效的响应。
但是能否在flask中对多个文件做出响应?
看来这种自定义响应应该转换为json类型,如果可以的话,如何“ jsonify”呢?

1 个答案:

答案 0 :(得分:0)

我们可以使用 here 所示的 JavaScript 来下载文件。通过将其与 HTML 结合,我们可以创建一个 html 模板,该模板将下载文件然后关闭窗口。

//download.js
function urlToBase64(url){
    return new Promise((resolve, reject) => {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'blob';
        request.onload = function() {
            var reader = new FileReader();
            reader.readAsDataURL(request.response);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        };
        request.send();
    });
}

function download(filename, data){
      //For data, we need a base64 data url
    var a = document.createElement('a');
    a.setAttribute("href", data);
    a.setAttribute("download", filename);

    a.hidden = true;
    document.body.appendChild(a);
      a.click();
    document.body.removeChild(a);
}

for (file of document.querySelectorAll('.download')){
    download(file.filename, file.url);
}
<head>
    <div class="download" filename="file1.txt" url="data:text/plain;charset=utf-8,hello%20world"></div>
    <div class="download" filename="file2.txt" url="data:text/plain;charset=utf-8,this%20is%20another%20text%20file"></div>
    <script src="download.js"><script>
</head>
<body>
</body>

此代码段采用 div 元素并使用它的 filenameurl 属性下载文件。 (由于 Stackoverflow 阻止它下载文件,该代码段不起作用。)