如何使用carrierwave多文件上传文件作为zip下载?

时间:2015-03-23 16:37:27

标签: ruby-on-rails carrierwave

我正在处理多个文件上传,我可以上传多个文件。现在我的要求是将特定帖子ID的文件下载为zip。

post.rb:

class Post < ActiveRecord::Base
  has_many :post_attachments
  accepts_nested_attributes_for :post_attachments
end 

post_attahment.rb:

class PostAttachment < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
  belongs_to :post
end

avatar_uploader.rb:

class AvatarUploader < CarrierWave::Uploader::Base

 storage :file
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

这是我的帖子控制器:

class PostsController < ApplicationController
  before_action :set_post, only: [:show]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
    @post_attachments = @post.post_attachments.all
  end

  # GET /posts/new
  def new
    @post = Post.new
    @post_attachment = @post.post_attachments.build
  end



  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        params[:post_attachments]['avatar'].each do |a|
          @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
        end
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
      else
        format.html { render action: 'new' }
      end
    end
  end




  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
  def post_params
    params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
  end
end

帖/ show.html.erb:

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<% @post_attachments.each do |p| %>
    <%= image_tag p.avatar_url %>
    <%= link_to "Edit Attachment", edit_post_attachment_path(p) %>
<% end %>

对于单个文件上传,我在控制器中使用了下载方法:

  def download
      respond_to do |format|
        format.html {
            if params[:post_id].nil?
                redirect_to :back
            else
              begin
                post= Post.find(params[:post_id])
                attachment_file = File.join('public', post.avatar.url)
                if File.exists?(attachment_file)
                  send_file attachment_file, :disposition => 'attachment'
                else
                  redirect_to :back
                end
              rescue Exception => error
                redirect_to :back
              end
            end
        }
      end
  end

在模型 mount_uploader:avatar,AvatarUploader 和索引中:

 <%= link_to image_tag("download.png"), download_post_path(post.id) %>

以zip格式下载多个文件的条件是什么?

0 个答案:

没有答案