代码之家  ›  专栏  ›  技术社区  ›  Victor Policastro

使用回形针gem上传多幅图像并更新图像

  •  0
  • Victor Policastro  · 技术社区  · 7 年前


    我正在尝试将多个图像上传到我的系统。我正在使用 paperclip gem

    1-如何在散列中保存多个图像?
    2-如何更新/插入图像?

    用户必须选择他想要更新的所有产品( check_box_tag )然后选择他想要上传的所有图像。如果产品与图像同名,则保存更改。

    altprod product_控制器中的功能。它涉及行动,但唯一重要的部分是重要性:

    def altprod
        case params[:commit]
        (...)
        when "Import"
          slctProd = params[:selected_products]
          slctProd.each do |prod|
            if prod.eql? File.basename(params[:image].original_filename, ".*")
              #Here is the problem :'(
              Product.where(code: prod).update(image: :image)
            end
          end
          redirect_to products_url, notice: 'Insert/update images succeeded.'
        end
      end
    

    下面是上传文件的代码:

    <%= form_tag altprod_products_path, multipart: true  do %>
        (...)
        <%= file_field_tag :image, multiple: true %>
        <%= submit_tag "Import", method: :post %>
        <br/>
        (...)
    <% end %>
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   t s    7 年前

    试试这个。 在这里 avatar 是图像字段名。我认为您正确地运行了回形针命令来生成图像模型。

    #Product Controller
    
    if params[:images]
      params[:images].each { |image|
        @product.create_image(avatar: image, user_id: current_user.id)
      }
    end
    

    类型

    <%= file_field_tag "images[]", type: :file,:required => true %>
    

    belongs_to :product
    has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png",
                         size: { in: 0..1000.kilobytes },
                          url: "/system/:hash.:extension",
                  hash_secret: "abc123"
    validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
    validates_attachment :avatar, :presence => true,
    
          :size => { :in => 0..5000.kilobytes}
    

    产品型号

    has_many :images, dependent: :destroy
    

    [#<ActionDispatch::Http::UploadedFile:0x007f90b22c5340 @tempfile=#<Tempfile:/tmp/RackMultipart20170929-7646-eqf009.jpeg>, @original_filename="job_post.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"book_image[]\"; filename=\"job_post.jpeg\"\r\nContent-Type: image/jpeg\r\n">, #<ActionDispatch::Http::UploadedFile:0x007f90b22c52f0 @tempfile=#<Tempfile:/tmp/RackMultipart20170929-7646-1qhrsy8.jpeg>, @original_filename="query.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"book_image[]\"; filename=\"query.jpeg\"\r\nContent-Type: image/jpeg\r\n">]