2017-10-12 120 views
1

我收到一個請求參數文件通過一個標準的文件輸入通行證文件活動作業/後臺作業

def create 
    file = params[:file] 
    upload = Upload.create(file: file, filename: "img.png") 
end 

然而,對於較大的上載,我想這樣做在後臺作業。 Sidekiq或Resque等流行的後臺作業選項取決於Redis來存儲參數,因此我不能只通過redis傳遞文件對象。

我可以使用Tempfile,但在某些平臺上,如Heroku,本地存儲不可靠。

我有什麼選擇使它在「任何」平臺上可靠?

回答

0

首先,您應該保存存儲上的文件(本地或AWS S3)。 然後通過filepath或uuid作爲後臺作業的參數。

我強烈建議避免在參數上傳遞Tempfile。這會將對象存儲在可能會過時的內存中,從而導致陳舊的數據問題。

1

我建議直接上傳到像Amazon S3這樣的服務,然後按照您認爲適合的背景作業處理文件。

當用戶上傳文件時,您可以放心確保它會安全地存儲在S3中。您可以使用專用存儲桶來禁止公衆訪問。然後,在後臺任務中,您可以通過傳遞文件的S3 URI來處理上載,並讓後臺工作人員下載文件。

我不知道你的後臺工作人員用這個文件做什麼,但不言而喻,重新下載它可能沒有必要。畢竟它存儲在某個地方。

我以前用carrierwave-direct寶石取得了成功。既然你提到Heroku,他們有一個詳細的guide上傳文件直接到S3。

0

沒有臨時文件

這聽起來像你想要加快圖像上傳或推到後臺。這裏是my suggestions from another post。也許他們會幫助你,如果這就是你想要的。

我發現這個問題的原因是因爲我想保存一個CSV文件,有我的後臺作業添加到數據庫中,在該文件中的信息。

我有一個解決方案。

因爲你的問題有點不清楚,我懶得張貼自己的問題和回答我的問題,我只是發佈答案在這裏。笑

像其他帥哥說,節省一些雲存儲服務的文件。對於亞馬遜,你需要:

# Gemfile 
gem 'aws-sdk', '~> 2.0' # for storing images on AWS S3 
gem 'paperclip', '~> 5.0.0' # image processor if you want to use images 

你也需要這個。使用在production.rb

# config/environments/development.rb 
Rails.application.configure do 
    config.paperclip_defaults = { 
    storage: :s3, 
    s3_host_name: 's3-us-west-2.amazonaws.com', 
    s3_credentials: { 
     bucket: 'my-bucket-development', 
     s3_region: 'us-west-2', 
     access_key_id: ENV['AWS_ACCESS_KEY_ID'], 
     secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'] 
    } 
    } 
end 

相同的代碼,但不同的鬥名字你還需要遷移

# db/migrate/20000000000000_create_files.rb 
class CreateFiles < ActiveRecord::Migration[5.0] 
    def change 
    create_table :files do |t| 
     t.attachment :import_file 
    end 
    end 
end 

和模型

class Company < ApplicationRecord 
    after_save :start_file_import 

    has_attached_file :import_file, default_url: '/missing.png' 
    validates_attachment_content_type :import_file, content_type: %r{\Atext\/.*\Z} 

    def start_file_import 
    return unless import_file_updated_at_changed? 
    FileImportJob.perform_later id 
    end 
end 

和工作

class FileImportJob < ApplicationJob 
    queue_as :default 

    def perform(file_id) 
    file = File.find file_id 
    filepath = file.import_file.url 

    # fetch file 
    response = HTTParty.get filepath 
    # we only need the contents of the response 
    csv_text = response.body 
    # use the csv gem to create csv table 
    csv = CSV.parse csv_text, headers: true 
    p "csv class: #{csv.class}" # => "csv class: CSV::Table" 
    # loop through each table row and do something with the data 
    csv.each_with_index do |row, index| 
     if index == 0 
     p "row class: #{row.class}" # => "row class: CSV::Row" 
     p row.to_hash # hash of all the keys and values from the csv file 
     end 
    end 
    end 
end 

在你的公司ntroller

def create 
    @file.create file_params 
end 

def file_params 
    params.require(:file).permit(:import_file) 
end