没有临时文件
听起来您想加快图片上传速度或将其推送到后台。这里是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中使用相同的代码但不同的bucket名称
# 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
在你的控制器中
def create
@file.create file_params
end
def file_params
params.require(:file).permit(:import_file)
end