【问题标题】:Carrierwave: Process Temp file and then upload via fogCarrierwave:处理临时文件,然后通过雾上传
【发布时间】:2013-09-05 08:38:43
【问题描述】:

我正在处理用户上传的 pdf,方法是从中提取文本并将输出保存在文本文件中以供以后处理。

我在本地将 pdf 存储在我的公用文件夹中,但是当我在 Heroku 上工作时,我需要使用 S3。

我认为是pdf路径有问题,所以我加入了

如果 Rails.env.test? || Rails.env.cucumber?

但我还是收到了

ArgumentError(输入必须是类似 IO 的对象或文件名):

有没有办法将 pdf 临时存储在 Heroku 上我的 root/tmp 文件夹中,从中获取文本,然后完成后,将文档上传到 S3?

def convert_pdf
    if Rails.env.test? || Rails.env.cucumber?
        pdf_dest = File.join(Rails.root, "public", @application.document_url)
    else
        pdf_dest = @application.document_url
    end
    txt_file_dest = Rails.root + 'tmp/pdf-parser/text'

    document_file_name = /\/uploads\/application\/document\/\d{1,}\/(?<file_name>.*).pdf/.match(@application.document_url)[:file_name]

    PDF::Reader.open(pdf_dest) do |reader|
        File.open(File.join(txt_file_dest, document_file_name + '.txt'), 'w+') do |f|
            reader.pages.each do |page|
                f.puts page.text
            end
        end
    end
end

【问题讨论】:

    标签: ruby-on-rails pdf heroku amazon-s3 carrierwave


    【解决方案1】:

    您需要在上传器中设置自定义处理器。最重要的是,由于输出文件 (.txt) 的扩展名与输入文件 (.pdf) 的扩展名不同,因此您需要更改文件名。以下内容属于您的上传器:

    process :convert_to_text
    
    def convert_to_text
      temp_dir = Rails.root.join('tmp', 'pdf-parser', 'text')
      temp_path = temp_dir.join(filename)
    
      FileUtils.mkdir_p(temp_dir)
    
      PDF::Reader.open(current_path) do |pdf|
        File.open(temp_path, 'w') do |f|
          pdf.pages.each do |page|
            f.puts page.text
          end
        end
      end
    
      File.unlink(current_path)
      FileUtils.cp(temp_path, current_path)
    end
    
    def filename
      super + '.txt' if original_filename.present?
    end
    

    我没有运行这段代码,所以可能有一些错误,但至少应该让你知道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 2012-06-15
      • 1970-01-01
      • 2017-09-22
      相关资源
      最近更新 更多