加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 将文件上传到服务器并将路径存储在Ruby on Rai

发布时间:2020-12-17 03:28:54 所属栏目:百科 来源:网络整理
导读:我对ROR很新.我有一项任务要完成: 这是模型: class File::DataImport ActiveRecord::Base attr_accessible :created_by,:file_name,:file_source,:updated_at,:updated_byend 这是控制器: class Files::DataImportsController ApplicationController def
我对ROR很新.我有一项任务要完成:

这是模型:

class File::DataImport < ActiveRecord::Base
  attr_accessible :created_by,:file_name,:file_source,:updated_at,:updated_by
end

这是控制器:

class Files::DataImportsController < ApplicationController
  def index
  end

  def new
  end
end

我的观点是索引和新的.

我想要一个字段来上传数据.数据应存储在服务器中,并将文件路径保存到指定列file_name中的数据库中.该路径应默认为所有上传文件.

我被困在如何开始.请帮我找到解决方案,我将从中学习.

提前致谢.

解决方法

分贝/迁移/ 20110711000004_create_files.rb

class CreateFiles < ActiveRecord::Migration
def change
  create_table :files do |t|
  t.string :name
  # If using MySQL,blobs default to 64k,so we have to give
  # an explicit size to extend them
  t.binary :data,:limit => 1.megabyte
  end
end
end

应用程序/控制器/ upload_controller.rb

class UploadController < ApplicationController
 def get
 @file = File.new
 end
 end

应用程序/视图/上传/ get.html.erb

<% form_for(:file,url: {action: 'save'},html: {multipart: true}) do |form| %>
Upload your file: <%= form.file_field("uploaded_file") %><br/>
<%= submit_tag("Upload file") %>
<% end %>

应用程序/模型/ file.rb

class File < ActiveRecord::Base
def uploaded_file=(file_field)
self.name = base_part_of(file_field.original_filename)
self.data = file_field.read
end
def base_part_of(file_name)
File.basename(file_name).gsub(/[^w._-]/,'')
end
end

应用程序/控制器/ upload_controller.rb

def save
@file = File.new(params[:file])
if @file.save
redirect_to(action: 'show',id: @file.id)
else
render(action: :get)
end
end

应用程序/控制器/ upload_controller.rb

def file
@file = File.find(params[:id])
send_data(@File.data,filename: @File.name,disposition: "inline")
end

应用程序/控制器/ upload_controller.rb

def show
@file = File.find(params[:id])
end

应用程序/视图/上传/ show.html.erb

<h3><%= @file.name %></h3>
<img src="<%= url_for(:action => 'file',:id => @file.id) %>"/>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读