从API下载文件

时间:2018-05-10 14:47:50

标签: python rest flask download

我将文件从网页发送到Flask服务器,然后对其执行一些转换,然后我想返回转换后的文档,以便用户可以下载它。我有一个按钮,这将发送POST请求:

fileUpload: function(file) {
  var formData = new FormData();
  formData.append('file',file);
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", () => {
    console.log("asdf");
  });
  xhr.open("POST", "http://localhost:7733/receivedoc");
  xhr.send(formData);
}

然后在服务器上,我进行转换并想要返回一个文件:

...
#Transformations, save file to the file system
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

但是,我的浏览器中没有任何文件下载。没有错误,请求似乎经历好了。请求标头是

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,hu;q=0.7,cs;q=0.6,sk;q=0.5,de;q=0.4
Connection: keep-alive
Content-Length: 114906
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycEQwQtGAXe1ysM9b
DNT: 1
Host: localhost:7733
Origin: http://localhost:5000
Referer: http://localhost:5000/

请求有效负载:

------WebKitFormBoundarycEQwQtGAXe1ysM9b
Content-Disposition: form-data; name="file"; filename="response.xls"
Content-Type: application/octet-stream


------WebKitFormBoundarycEQwQtGAXe1ysM9b--

response.xls正好是我想要下载的文件。我该如何下载?

更新 - 尝试实施Joost的解决方案。我这样做:

@app.route('/receivedoc', methods=['POST', 'GET', 'OPTIONS'])
@crossdomain(origin='*')
def upload_file():
    if request.method == 'POST':
#TRANSFORMING FILE, then saving below:
            writer = pd.ExcelWriter(filename)
            df_output.to_excel(writer,'Pacing', index=False)
            writer.save()
            return send_from_directory(directory=app.config['UPLOAD_FOLDER'], filename=filename)

    if request.method == 'GET':
        prefixed = [filename for filename in os.listdir(app.config['UPLOAD_FOLDER']) if filename.startswith("PG PEIT")]
        filename = max(prefixed)
        print("what what")
        return render_template_string('''<!DOCTYPE html>
            <html lang="en">
            <head>
            <meta charset="utf-8">
            <title>Your file is ready</title>
            </head>
            <body>
            <form enctype="multipart/form-data" method="post" name="fileinfo">
            <input type="text" name="fname" required />
            <input type="submit" value="request the file!" />
            </form>
            <script>
            function saveBlob(blob, fileName) {
                var a = document.createElement("a");
                a.href = window.URL.createObjectURL(blob);
                a.download = fileName;
                document.body.appendChild(a); // won't work in firefox otherwise
                a.click();
            }
            var form = document.forms.namedItem("fileinfo");
            form.addEventListener('submit', function(ev) {
            var oData = new FormData(form);
            var oReq = new XMLHttpRequest();
            oReq.responseType = 'blob';
            oReq.open("POST", "{{url_for('upload_file')}}", true);
            oReq.onload = function(oEvent) {
                if (oReq.status == 200) {
                var blob = oReq.response;
                var fileName = 'response.xml'
                saveBlob(blob, fileName);
                } else {
                alert("Error " + oReq.status + " occurred")
                }
            };
            oReq.send(oData);
            ev.preventDefault();
            }, false);
            </script>
            </body>
            </html>
            ''')

这会给我一个很好的.html响应,但该文件仍然无法下载:

enter image description here

我误解了什么?

1 个答案:

答案 0 :(得分:0)

这主要是一个javascript问题,python没有那么多与它有关。几个星期前我遇到了同样的问题,所以我决定做一个工作应用程序的小例子。主要技巧是将数据保存在js中,使用数据创建可下载链接,并使js单击它。

功能齐全的例子:

DisableFastUpToDateCheck
相关问题