我正在尝试通过send_from_directory()
或status_code=200
从Flask应用发送文件,但没有成功。
该请求返回一个带有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 -
这是服务器返回的内容
{{1}}
我已验证文件确实已创建并保存,并且已验证如果路径错误或文件不存在,则上述最后一行将返回错误。
为什么会这样?
答案 0 :(得分:0)
您的form
有enctype = "multipart/form-data"
吗?
您是否检查请求中是否存在文件?
答案 1 :(得分:0)
弄清楚了。我正在使用customer_id
处理我的user = current_user
stripe_customer = Stripe::Customer.retrieve(user.stripe_id)
stripe_subscription = stripe_customer.['data'][0].delete
请求。似乎javascript axios
请求无法返回文件。
我找到了一种解决方法,将POST
作为POST
返回到我的JavaScript中,并使用该路径调用'/path/to/file/spreadsheet.xlsx'
。
然后,我只需要创建一个标准的Flask JSON
路由window.open()
,就可以使用该GET
函数通过url从目录中返回文件。
答案 2 :(得分:0)
我也遇到过这种问题。 我还使用flask和send_file()库将文件发送到UI以供用户下载。
我只是使用以下烧瓶来发送文件。
@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无法使用此响应。
added a snip of Response I was getting with above code:
浏览文档https://tedboy.github.io/flask/generated/flask.send_file.html之后,我发现excel文件(.xlsx)或(.xls)的一个参数'mimetype'应该作为参数传递。注意:(.xlsx和.xls)的mimetype是不同的plz,请点击此链接查找不同文件的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类型来捕获和解码响应,并将其放入excel文件中进行下载。 在UI中,contentType应与烧瓶send_file()中使用的相同mimetype contentType ='application / vnd.openxmlformats-officedocument.spreadsheetml.sheet';
通过这种方式,您可以下载Excel文件。