Ajax POST 到 flask 下载二进制文件(正在使用 cytoscape)

Ajax POST to flask to download a binary (cytoscape in use)

我正在使用 cytoscape.js 创建一个可以快速下载文件的菜单。我正在使用 Ajax POST 将文件名传回 flask 以便下载。出于某种原因,我可以取回所有信息,但无论出于何种原因,我都无法下载文件。到目前为止,我已经尝试了两种方法。

AJAX Post:

{{
                    content: 'Download',
                    select: function(ele) {{
                        //this is to get the name of URI
                        var loc = window.location.pathname
                        var postData = {{
                             "element": ele.id(),
                             "source": loc
                         }}
                        $.ajax({{
                            url: '/get_file',
                            type: "POST",
                            contentType: 'application/json',
                            data: JSON.stringify(postData),
                            dataType: 'json',
                            success: function(response) {{
                                console.log("got it!")
                            }},
                            error: function(xhr) {{
                                console.log("Nope!")
                            }}
                        }})

现在对于 flask 后端,我们有方法一,注释部分显示方法 2 和 3(在 if 循环中(if os.path.isfile(SAVE_PATH)):

@app.route('/get_file', methods=['POST'])
def get_file():
    print("This is request data: {}".format(request.data))
    requests = request.get_json()
    element = requests['element']
    source = requests['source']
    #this is where loc is retrieved from ajax post, in format of /static/{filename}.html
    for change in ['/static/', '.html']:
        if change in source:
            source = source.replace(change,"")
    print("source: {}".format(source))
    SAVE_PATH = os.path.curdir + "/results/" + source + "/" + element
    SAVE_DIRECTORY = os.path.curdir + "/results/" + source + "/"
    if os.path.isfile(SAVE_PATH):
        downloaded_file = open("{}".format(SAVE_PATH), 'rb').read()
        #res = send_from_directory(SAVE_PATH.replace("./", ""), element, attachment_filename=element, mimetype="application/octet-stream", as_attachment=True)
        #res = send_file(SAVE_PATH, as_attachment=True, attachment_filename=element, mimetype='application/octet-stream')
        #return res
        return Response(
            downloaded_file,
            mimetype="application/octet-stream",
            headers={"Content-disposition":
                     "attachment; filename={}".format(element)})
    else:
        print("failed")
    return "failed"

现在我得到了所有正确的响应,当我打印 downloaded_file 时,我得到了二进制输出,但无论出于何种原因,它就是没有下载。

看来你可以在前端构建下载路径并直接请求文件,就像这样:

location = loc.split("/");
path = "results/" + location[location.length - 1].split(".")[0] + "/" + ele.id();
window.location.href = path;