繁体   English   中英

Flask send_file / send_from_directory 返回 200 状态代码但不是文件

[英]Flask send_file / send_from_directory returning 200 status code but not the file

我正在尝试通过send_file()send_from_directory()从我的 Flask 应用程序发送文件,但没有成功。

该请求返回status_code=200的响应,但没有下载文件。 我已经验证了这些函数在文件或目录不存在时返回错误时的工作

这是我函数的最后一行。 它处理POST请求,并在保存后返回一个文件。

# openpyxl stuff above
wb.save(app.instance_path + '/path/to/file/spreadsheet.xlsx') 

return send_file(current_dir + '/path/to/file/spreadsheet.xlsx')

这是从服务器返回的内容

127.0.0.1 - - [21/Apr/2019 20:05:26] "POST /api/admin/export_bookings HTTP/1.1" 200 -

我验证了文件确实正在创建和保存,并且我已经验证了如果路径错误或文件不存在,上面的最后一行会返回错误。

为什么会这样?

你的formenctype = "multipart/form-data"吗?

您是否检查了请求中是否存在该文件?

弄清楚了。 我正在使用axios来处理我的POST请求。 似乎 javascript POST请求没有返回文件的能力。

我找到了一种解决方法,将'/path/to/file/spreadsheet.xlsx'作为JSON返回到我的 javascript 并使用该路径调用window.open()

然后我只需要创建一个标准的 Flask GET路由@bp.route('/path/to/file/<filename>) ,它使用send_file()函数通过 url 从目录中返回文件。

我也遇到过这样的问题。 我还使用 Flask 和 send_file() 库将文件发送到 UI 供用户下载。

我只是使用flask发送文件,如下所示。

@app.run('/download_any_file',methods=['POST'])
def download():
  path='folder_path_where_file_exist'
  filename='abcde.xlsx' # i am getting this filename from UI
  full_path=path+'/'+ filename
  return send_file(full_path,as_attachment=True)

我从这个 API 得到了一些响应,但 UI 由于某种原因无法使用这个响应。

添加了我使用上述代码获得的响应片段:

通过文档https://tedboy.github.io/flask/generated/flask.send_file.html 后,我发现 excel 文件(.xlsx)或(.xls)的一个参数“mimetype”应该作为参数传递. 注意:(.xlsx 和 .xls)的 mimetype 是不同的,请按照此链接查找不同文件的 mimetype https://docs.microsoft.com/en-us/archive/blogs/vsofficedeveloper/office-2007-file-format -mime-types-for-http-content-streaming-2

我最终更改了我的代码,如下所示:

@app.run('/download_any_file',methods=['POST'])
def download():
  path='folder_path_where_file_exist'
  filename='abcde.xlsx' # i am getting this filename from UI
  full_path=path+'/'+ filename
  return send_file(full_path,as_attachment=True,mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

现在应该在 UI 端使用相同的 mime-type 来捕获和解码响应并将其放入 excel 文件中下载。 在 UI contentType 应该是在flask send_file() contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'中使用的相同mimetype;

这样你就可以下载一个excel文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM