簡體   English   中英

使用模型ID直接在“新”操作中上傳S3?

[英]Using model ID for direct S3 upload in 'new' action?

我目前正在使用jQuery文件上傳直接在我的rails應用程序中上傳到S3。

我有一個pm_report,里面有3張照片,並且正在上傳它們,而在現有報告中沒有任何問題。

當我嘗試創建新報告時會出現問題,因為它會嘗試在將報告保存到數據庫之前為要上傳的照片建立路徑(該報告尚無ID)。

我所擁有的

pm_reports_controller.rb

...
before_action :set_s3_direct_post, only: [:new, :edit, :create, :update]
...
private
...
  def set_s3_direct_post
      @s3_direct_post = S3_BUCKET.presigned_post(key: "pm_reports/#{@pm_report.id}/${filename}", success_action_status: '201', acl: 'private')
  end

我要完成的工作 :將報告的3張圖像保存在S3上pm_reports中的自己的文件夾中。

有沒有一種方法可以解決此問題,或者可以采用其他方法?

編輯 :找到了一個更好的解決方案。

邏輯是這樣的。

為您的應用創建第二個存儲桶,將規則設置為在x天內自動刪除。 使用jQuery文件直接上傳到S3臨時存儲區。 然后在模型中添加一個after_commit回調,以便您可以使用aws-sdk gem將對象從一個存儲桶復制到另一個存儲桶,從而將臨時上傳路徑更改為其最終路徑。

這使我可以為對象添加一個固定名稱,因為它適合我的問題,因此,在進行回調之后,我設置了最終路徑,然后將其顯示在視圖上的image_tag上。

如果有人請我詳細說明並放一些代碼。



我使用uuid作為Brent在他的評論中指出的另一種方法。

我不得不改變一些事情:

添加遷移

class AddUuidToPmReports < ActiveRecord::Migration
   def change
     add_column :pm_reports, :uuid, :uuid
   end
end

更改pm_reports_controller.rb,以便在“ new”操作之后和“ edit”操作之前設置s3直接發布。 另外,更改預簽名帖子的鍵以使用uuid並將其作為強參數接受。

...
before_action :set_s3_direct_post, only: :edit
...
def new
    @pm_report = PmReport.new
    @pm_report.uuid = SecureRandom.uuid
    set_s3_direct_post
end
...
private
...
def pm_report_params
      params.require(:pm_report).permit( ..., :uuid)
    end

  def set_s3_direct_post
      @s3_direct_post = S3_BUCKET.presigned_post(key: "pm_reports/#{@pm_report.uuid}/${filename}", success_action_status: '201', acl: 'private')
  end

最后,為要通過表單傳遞的uuid添加一個隱藏字段,以便我們保存它。

查看/pm_reports/_form.html.erb

<%= form_for @pm_report, ... %>
...
<%= f.hidden_field(:uuid) %>
...
<%= f.submit %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM