setting the filename for a downloaded file in a rails application

前端 未结 3 1336
南方客
南方客 2020-12-10 12:52

I have a controller action that allows a user to download a file with an extension of .ppt . It\'s not really a powerpoint binary, just an xml-ish format that powerpoint can

相关标签:
3条回答
  • 2020-12-10 13:35

    Ok. This is an answer for a very old question, but as of Rails 3.2 the most simple way is to set it like:

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @product }
      format.csv { send_data @product.to_csv, :filename => "New-Product-filename.csv" }
      format.xls 
    end
    

    Source API Doc

    0 讨论(0)
  • 2020-12-10 13:36

    A possible example:

    def show
        @item = Item.find(params[:id])
        respond_to do |format|
            format.html # show.html.erb
            format.ppt {
                response.headers['Content-Disposition'] = "attachment; filename=\"#{@item.filename}.ppt\""
            } # show.ppt.erb
            format.xml  { render :xml => @item }
        end
    end
    
    0 讨论(0)
  • 2020-12-10 13:54

    You could use send_data:

    send_data pptdata, :filename => 'your_file_name.ppt', 
       :disposition => 'inline', :type => "multipart/related"
    

    Another advantage of this is you can use x-sendfile, so that you're mongrel/thin isn't waiting while the client downloads the data.


    Another option would be to have a route like:

    /elements/3/files/foo.ppt

    Then in your show method for the FilesController you can send whatever the id parameter would be.

    0 讨论(0)
提交回复
热议问题