Rails 如何知道 send_file 何时完成
由于需要一些时间来准备要下载的数据的内容,所以我想在用户提交请求时显示一条消息“正在准备下载文件”
然后当文件准备好时,我使用send_file发送数据
一旦完成完成,我需要清除消息,
非常感谢
As it takes some time to prepare the content of the data to be downloaded, I want to show a message "Preparing file to download" when the user submits the request
Then when the file is ready, I use send_file to send the data
Once it's done, I need to clear the message
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是我要做的。
1.创建一个prepare_file 操作
首先,我将创建一个操作,其工作只是创建文件,而不是渲染HTML,而是渲染一个带有所创建文件名称的JSON 对象。
2.使用AJAX 调用prepare_file 操作
在客户端上,当用户单击下载文件时,您会显示消息“正在准备下载...”,然后只需对该操作执行AJAX 请求即可。您将通过 AJAX 返回的响应是创建的文件的名称。
3.重定向到文件下载
最后,您可以隐藏准备下载消息,并使用创建的文件名通过 JavaScript 将浏览器重定向到文件下载。您将在此操作中使用
send_file
。我知道,在这个问题中,您还希望能够在文件下载时向用户显示一条消息,并在下载完成时向用户显示另一条消息。但是,除非您编写自己的客户端下载管理器,否则这是不可能的。浏览器完全处理文件下载,用户将在浏览器中看到文件正在下载以及进度如何。所以,我理解你的想法,但你不应该觉得用户没有被告知正在发生的事情。
至少使用此解决方案,您可以在准备文件时向他们显示一条消息,然后一旦该消息消失,他们就会从浏览器获取下载文件对话框。
如果您需要有关如何执行此操作的实际代码示例的帮助,请告诉我。
Here is what I would do.
1. Create a prepare_file action
First, I would create an action whose job would just be to create the file and rather than rendering HTML, it would render a JSON object with the name of the file that was created.
2. Use AJAX to call the prepare_file action
On the client, when the user clicks to download the file, you display the message, "Preparing download..." and just do an AJAX request to that action. The response you'll get back via AJAX is the name of the file created.
3. Redirect to the file download
Finally, you can hide the preparing download message and redirect the browser to the file download via JavaScript with the name of the file that was created. You would use
send_file
in this action.I know that, in the question, you also wanted to be able to display to the user a message when the file is downloading and another message when it is finished. However, this isn't possible unless you write your own client-side download manager. The browser handles file downloads entirely and the user will see in the browser that the file is downloading and what the progress is. So, I understand where you're coming from, but you shouldn't feel like the user isn't being informed of what's happening.
At least with this solution, you're displaying a message to them when the file is being prepared and then once that message disappears, they'll get the download file dialog from the browser.
If you need help with actual code samples of how to do this, let me know.