将文件上传到服务器并将路径存储在 Ruby on Rails 的数据库中 [英] Uploading File into Server and store the path in database in Ruby on Rails

查看:49
本文介绍了将文件上传到服务器并将路径存储在 Ruby on Rails 的数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 ROR 很陌生.我有一个任务要完成:

I am very new to ROR. I have a task to finish:

这是模型:

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

我拥有的视图是 indexnew.

And the views I have are index and new.

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

I want a field to upload data. The data should be stored in the server and save the filepath into the database in a specified column file_name. The path should be default to all uploading files.

我对如何开始感到困惑.请帮我找到解决方案,我会从中吸取教训.

I am stuck with how to start. Please help me to find the solution and I will learn from this.

提前致谢.

推荐答案

db/migrate/20110711000004_create_files.rb

db/migrate/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

app/controllers/upload_controller.rb

app/controllers/upload_controller.rb

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

app/views/upload/get.html.erb

app/views/upload/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 %>

app/models/file.rb

app/models/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

app/controllers/upload_controller.rb

app/controllers/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

app/controllers/upload_controller.rb

app/controllers/upload_controller.rb

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

app/controllers/upload_controller.rb

app/controllers/upload_controller.rb

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

app/views/upload/show.html.erb

app/views/upload/show.html.erb

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

这篇关于将文件上传到服务器并将路径存储在 Ruby on Rails 的数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆