下载Python3 Flask生成的ZipFile的Javascript按钮

2vuwiymt  于 2022-12-01  发布在  Python
关注(0)|答案(1)|浏览(129)

我正在Ubuntu 18.04上使用Python 3.7生成一个ZipFile,并使用Flask 1.0.2提供它。我知道Flask代码可以工作,因为我可以在浏览器中显式键入端点,并获得一个有效的ZipFile,我可以在Windows 10上解压缩。我现在尝试使用Javascript代码通过单击按钮下载ZipFile。问题是生成的文件被声明为“Corrupt”由Windows下载,且无法解压缩。如何让Javascript正确下载档案?
Flask代码如下所示:

@app.route("/get_new_training_data", methods=["GET"])
def create_and_serve_training_data_zipfile():

    # Define the location of the new training data
    newDataLocation = "%s" % (configuration.NEW_TRAINING_DATA_LOCATION)

    # Ensure it exists or throw and error
    if os.path.isdir(newDataLocation):

        print("[%s] Creating new ZipFile for download from: %s" % (os.path.basename(__file__), newDataLocation))

        # Create a zipfile in memory and send it back to the user
        # The zipfile will contain the training data collected through
        # the webbrowser button controls
        try:

            memoryFile = BytesIO()
            with zipfile.ZipFile(memoryFile, 'w', zipfile.ZIP_DEFLATED) as zf:
                for root, dirs, files in os.walk(newDataLocation):
                    for file in files:
                        print("[%s] Adding file to ZipFile: %s" % (os.path.basename(__file__), file))
                        zf.write(os.path.join(root, file))
            memoryFile.seek(0)
            return send_file(memoryFile, mimetype='application/zip', attachment_filename='ImageData.zip', as_attachment=True)

        except Exception as err:

            newStatus = {"download_image_data": "Failed: Error Could not create Zipfile: %s"%(err)}

            print("[%s] Error downloading new Training Data - JSON Response is: %s" % (
            os.path.basename(__file__), newStatus))

            return jsonify(newStatus), 500

    else:

        newStatus = {"download_image_data": "Failed: Error Training Data directory does not exist"}

        print("[%s] Error downloading new Training Data - JSON Response is: %s" % (os.path.basename(__file__), newStatus))

        return jsonify(newStatus), 500

Javascript代码如下所示:

// Add an on click for the download data button
var downloadTrainingDataButton = document.getElementById("downloadTrainingData");
downloadTrainingDataButton.onclick = function() {

    console.log("Downloading New Training Data ...");

    // Do a web request to download a zip file of the training data
    var logRequestXmlHttp = new XMLHttpRequest();
    logRequestXmlHttp.open( "GET", "http://{{host_ip}}/get_new_training_data", true ); // false for synchronous request
    logRequestXmlHttp.onload = function(e) {
        code = logRequestXmlHttp.response;

        if (logRequestXmlHttp.status == 200) {

            var blob = new Blob([this.response], {type: "application/zip"});
            var url = window.URL.createObjectURL(blob);
            var link = document.createElement('a');
            document.body.appendChild(link);
            link.style = "display: none";
            link.href = url;
            link.download = "ImageData.zip";
            link.click();

            setTimeout(() => {
            window.URL.revokeObjectURL(url);
            link.remove(); } , 100);

            console.log("Success downloading zip file");

        }

    };
    logRequestXmlHttp.onerror = function () {
        console.log("Error with downloading zip file: " + logRequestXmlHttp.responseText + " Code: " + code);
    };
    logRequestXmlHttp.send( null );

}
0yycz8jy

0yycz8jy1#

要下载文件,您可以使用锚标记上的HTML5 download属性,让它知道它需要下载某个资源,而不是导航到它。这可能是实现您所需的最简单的方法。
例如:

<a href="http://{{host_ip}}/get_new_training_data" download="training_data.zip">Download Training Data</a>

相关问题