0

我正在使用ROO gem 来解析用户在 Heroku 上上传的 Excel 文件(使用 AWS S3 的 Active Storage)。

由于我在 Heroku 上,我无法在文件系统上下载它然后解析它。如何从 HTTP 打开它?

模型

class Report < ApplicationRecord
  has_one_attached :search_report


def parsing_method(path_http)

   xlsx = Roo::Spreadsheet.open(path_http)
end 
4

2 回答 2

1

是的,您可以在 Heroku 中将其下载到文件系统中。

我怀疑空间很大,但是您应该可以使用临时文件。大多数系统先将上传内容存储到临时文件系统中,然后再将其推送到其他地方。

我已经在这样做了,因为 Roo 是能够从流中打开 Excel 文件的补丁,但没有其他类型(csv、ods 等)。

def create_temp_file
  filename = some_model.some_attachment.blob.filename
  @tmp = Tempfile.new([filename.base, filename.extension_with_delimiter], binmode: true)
  @tmp.write(ome_model.some_attachment.download)
  @tmp.rewind
  @tmp
end

# this is how you use it, note the rescue part
def access_the_file
  spreadsheet = Roo::Spreadsheet.open(create_temp_file)
  # access the spreadsheet as usual
rescue
  @tmp&.unlink
end

这保留了文件前缀和扩展名(对于让 Roo 推断文件是什么很重要)并确保文件在完成后被删除。

于 2021-05-26T07:22:06.720 回答
-1

在一个类似的应用程序中,我使用了这个:

def parsing_method(path_http)

   xlsx = Roo::Excelx.new(path_http, nil, :ignore)

end 

它应该适合你。

于 2019-07-10T15:02:39.787 回答