mardi 9 novembre 2021

ActiveStorage::FileNotFoundError in direct upload Attach using Amazon s3 presigned url

I'm using presigned_post for generating signed_url to upload file to s3 directly from client. The file is getting uploaded correctly and returning response with a generated blob_signed_id.

However , when I try to attach the file to the object , it is showing FileNotFoundError.

  def generate_url
    load_aws_credentials
    load_bucket
    blob = create_blob
    presigned_url = @s3_bucket.presigned_post(
      key: "#{Rails.env}/#{SecureRandom.uuid}/${filename}",
      success_action_status: "201",
      signature_expiration: (Time.now.utc + 15.minutes),
    )
    response = { url: presigned_url.url, url_fields: presigned_url.fields }
    response[:blob_signed_id] = blob.signed_id
    response
  end

  private
    attr_reader :blob_args

    def create_blob
      blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_args)
      blob
    end 

The blob is getting created and a signed_id is returned.

 def take_actions
        @message = ::Widget::Message.new(message_params)
        attach_files
        if @message.save
         ...
        else
         ...
        end
      end

  def attach_files
      if data["attachments"]
        data["attachments"].map do |attachment|
          @message.attachments.attach(attachment["blob_signed_id"])
        end
      end
    end

When I try to attach the file using the signed_id it is showing file not found.

Aucun commentaire:

Enregistrer un commentaire