简体   繁体   English

Rails 在文件上传期间从控制器更新进度条

[英]Rails update Progress Bar from Controller during file upload

I am still rather new to web programming so please bear with me.我对网络编程还是比较陌生,所以请耐心等待。

A rails 5.0 application currently works just fine and uploads a .csv file containing product inventory. rails 5.0 应用程序目前运行良好,并上传包含产品库存的 .csv 文件。 The problem is that if this file is very large it can take more than a minute to upload and the person on the client may think the server crashed or they lost the internet connection.问题是,如果这个文件非常大,上传可能需要一分钟以上,客户端上的人可能会认为服务器崩溃或他们失去了互联网连接。

The current implementation has a view with a form for selecting the file.当前的实现有一个视图,其中包含一个用于选择文件的表单。 Once selected, the controller reads in the file.选择后,控制器会读入文件。 The view is still sitting on the screen but control has shifted to the server at this point.视图仍然位于屏幕上,但此时控制权已转移到服务器。

I would like to have the server send an update to the view every N% of file read in, so the view could display and update a progress bar.我想让服务器每读入 N% 的文件就向视图发送一次更新,以便视图可以显示和更新进度条。 I think this is doable through AJAX calls and JSON or Javascript but am not certain about that.我认为这可以通过 AJAX 调用和 JSON 或 Javascript 来实现,但我不确定。 Is this a reasonable approach?这是一个合理的方法吗?

From what you described there seems to be 2 ways you can solve this.根据您的描述,似乎有两种方法可以解决此问题。

1) Use ActionCable and send progress messages out for that specific file. 1) 使用 ActionCable 并发送该特定文件的进度消息。 The message can contain a percentage of how much of the file has been processed.该消息可以包含已处理的文件量的百分比。 You can read on ActionCable and how to get started on that here .您可以在此处阅读 ActionCable 以及如何开始。

2) You can use ajax calls that happen on an interval. 2)您可以使用间隔发生的ajax调用。 Basically, there would be javascript code that calls a route within your app to check on the progress of the file that you are processing.基本上,将有 javascript 代码调用您的应用程序中的路由来检查您正在处理的文件的进度。 So in you controller action that processes the file, you will store the progress as you process the file.因此,在处理文件的控制器操作中,您将在处理文件时存储进度。 It can be in Redis , or in memory within the rails app.它可以在Redis 中,也可以在 rails 应用程序的内存中。 As long as it is something that is accessible from a different request.只要它是可以从不同的请求访问的东西。 It could possibly even be stored in the session even though I haven't tested using it like that before.它甚至可能存储在会话中,即使我之前没有像这样测试过使用它。 Your client side javascript would call the route that reports the progress on an interval.您的客户端 javascript 将调用以间隔报告进度的路由。

That's my thoughts on it at least.至少这是我的想法。 I hope that's helpful.我希望这会有所帮助。

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

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