首页 文章

通过API使用Activestorage(直接上传)

提问于
浏览
6

我想使用Rails作为移动应用程序(Android和iOS)的后端,其中一个要求是文件上传 .

我无法通过这种方式直接上传使用Activestorage找到任何资源 - 有没有人有示例或提示?

另一种选择 - 我认为 - 是对activestorage.js进行反向工程,并完成其所做的工作 . 但也许我不是第一个有这种需求的人......

1 回答

  • -1

    我使用rails作为后端,但我使用多态文档模型进行文档上传 . 最近我将paperclip api转换为文档模型的主动存储 . 下面的媒体链接解释了如何将活动存储作为后端上传与base64编码和解码集成 .

    Active Storage as Attachment in Rails API with base64 decoding

    这成为我的文档模型,具有活动存储库64解码多态: ``

    class Document < ApplicationRecord
      has_one_attached :doc
      belongs_to :documentable, polymorphic: true, optional: true
      attr_accessor :doc_contents
      attr_accessor :doc_name 
    
     after_create :parse_doc
      validate :doc_validations, on: :create 
    
     def parse_doc
        # If directly uploaded
        unless self.doc_contents.nil? || self.doc_contents[/(image/[a-z]{3,4})|(application/[a-z]{3,4})/] == ''
          content_type = self.doc_contents[/(image/[a-z]{3,4})|(application/[a-z]{3,4})/]
          content_type = content_type[/\b(?!./)./]
          contents = self.doc_contents.sub /data:((image|application)/.{3,}),/, ''
          decoded_data = Base64.decode64(contents)
          filename = self.doc_name || 'doc_' + Time.zone.now.to_s + '.' + content_type
          File.open("#{Rails.root}/tmp/images/#{filename}", 'wb') do |f|
            f.write(decoded_data)
          end
          self.doc.attach(io: File.open("#{Rails.root}/tmp/images/#{filename}"), filename: filename)
          FileUtils.rm("#{Rails.root}/tmp/images/#{filename}")
        end
      end 
    
     private 
    
     def doc_validations
        if self.doc_contents.nil?
          errors.add(:base, I18n.t('errors.documents.file_required'))
        end
      end
    end
    

相关问题