开发者社区 问答 正文

on rails 中利用carriwave 上传文件:报错

ruby新人,利用carriwave ,希望能达到的效果就是页面上一个按钮,点了之后能上传文件,之后能下载上传的文件,请问究竟应该怎么写? 如果能详细的解释下 models, controllers 和view分别应该写什么最好,谢谢了!


如果有更好地实现上传文件的方法也可以,请详细点告知怎么实现,谢谢!

展开
收起
kun坤 2020-06-14 09:39:28 446 分享 版权
阿里云 AI 助理回答

在Ruby on Rails中使用CarrierWave实现文件上传和下载功能是一个常见的需求。下面我将分步骤介绍如何设置模型(Model)、控制器(Controller)以及视图(View),并简要说明一个替代方案。

1. 添加依赖

首先,确保你的Gemfile中包含了carrierwave gem,并执行bundle install来安装它。

# Gemfile
gem 'carrierwave'

2. 创建Uploader

CarrierWave通过Uploader类来处理文件上传的逻辑。创建一个新的Uploader:

rails generate uploader File

这会生成一个名为FileUploader的文件。在这个文件中,你可以定义文件存储的位置、允许上传的文件类型等。

3. 修改Model

假设你有一个Document模型用于存储文件信息,你需要在模型中添加对CarrierWave的支持。

# app/models/document.rb
class Document < ApplicationRecord
  mount_uploader :file, FileUploader
end

这里,:file是数据库中的字段名,用来存储文件的元数据,而FileUploader是我们之前创建的Uploader类。

4. 设置Controller

上传文件

在相应的控制器中,创建一个方法来处理文件上传。

# app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
  def new
    @document = Document.new
  end

  def create
    @document = Document.new(document_params)
    if @document.save
      redirect_to document_path(@document), notice: "File uploaded successfully."
    else
      render :new
    end
  end

  private

  def document_params
    params.require(:document).permit(:file)
  end
end

下载文件

添加一个动作来提供文件下载。

def download
  @document = Document.find(params[:id])
  send_file @document.file.path, type: @document.file_content_type, disposition: 'attachment'
end

5. 视图设置

  • 上传表单

app/views/documents/new.html.erb中创建一个表单来上传文件。

<%= form_for @document, url: documents_path, html: {multipart: true} do |f| %>
  <%= f.file_field :file %>
  <%= f.submit "Upload" %>
<% end %>
  • 下载链接

在显示文档列表或详情页的地方,添加一个下载链接。

<%= link_to "Download", download_document_path(@document) %>

替代方案:Active Storage

Rails 5.2及以上版本引入了Active Storage作为内置的文件上传解决方案,它提供了更简洁的API。如果你的Rails版本支持,可以考虑使用Active Storage代替CarrierWave。

总结

以上就是使用CarrierWave在Ruby on Rails中实现文件上传和下载的基本步骤。记得根据实际情况调整路由、权限控制等细节。希望这对您有所帮助!

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答分类:
问答地址: