`

手把手学习Rails 文件上传(支持Rails2.3)

阅读更多
You may have a requirement in which you want your site visitors to upload a file on your server. Rails makes it very easy to handle this requirement. Now we will proceed with a simple and small Rails project.

As usual, let's start off with a new Rails application called upload. So let's create basic structure of the application by using simple rails command.

C:\ruby> rails upload


Now let's decide where you would like to save your uploaded files. Assume this is data directory inside your public section. So create this directory and check the permissions.

C:\ruby> cd upload
C:\ruby> mkdir upload\public\data


Our next step will be as usual, to create controller and models, so let's do that:
Creating Model:

Because this is not a database based application so we can keep name whatever is comfortable to us. Assume we have to create a DataFile model.

C:\ruby> ruby script/generate model DataFile
      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/data_file.rb
      create  test/unit/data_file_test.rb
      create  test/fixtures/data_files.yml
      create  db/migrate
      create  db/migrate/001_create_data_files.rb


Now we will create a method called save in data_file.rb model file. This method will be called by the application controller.

class DataFile < ActiveRecord::Base
  def self.save(upload)
    name =  upload['datafile'].original_filename
    directory = "public/data"
    # create the file path
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
  end
end


The above function will take CGI object upload and will extract uploaded file name using helper function original_filename and finally it will store uploaded file into "public/data" directory. You can call helper function content_type to know media type of the uploaded file.

Here File is a ruby object and join is a helper function will concatenate directory name alongwith file name and will return full file path.

Next, to open a file in write mode we are using open helper function provided by File object. Further we are reading data from the passed data file and writing into output file.
Creating Controller:

Now let's create a controller for our upload project:

C:\ruby> ruby script/generate controller Upload
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/upload
      exists  test/functional/
      create  app/controllers/upload_controller.rb
      create  test/functional/upload_controller_test.rb
      create  app/helpers/upload_helper.rb


Now we will create two controller functions first function index will call a view file to take user input and second function uploadFile takes file information from the user and passes it to the 'DataFile' model. We set the upload directory to the 'uploads' directory we created earlier "directory = 'data'".

class UploadController < ApplicationController
  def index
     render :file => 'app\views\upload\uploadfile.rhtml'
  end
  def uploadFile
    post = DataFile.save(params[:upload])
    render :text => "File has been uploaded successfully"
  end
end


Here we are calling function defined in model file. The render function is being used to redirect to view file as well as to display a message.
Creating View:

Finally we will create a view file uploadfile.rhtml which we have mentioned in controller. Populate this file with the following code:

<h1>File Upload</h1>
<%= start_form_tag ({:action => 'uploadFile'}, 
                        :multipart => true) %>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload" %>
<%= end_form_tag %>

Here everything is same what we have explained in earlier chapters. Only new tag is file_field which will create a button to select a file from user's computer.

By setting the multipart parameter to true, you ensure that your action properly passes along the binary data from the file.

Here important point to note is that we have given uploadFile method name in :action, which will be called when your will click Upload button.

This will show you a screen as follows:





Now you select a file and upload it, this file will be uploaded into app/public/data directory with the actual file name and a message will be displayed to you saying that "File has been uploaded successfully".

NOTE: If a file with the same name already exists in your output directory then it will be over-written.
Files uploaded from Internet Explorer:

Internet Explorer includes the entire path of a file in the filename sent, so the original_filename routine will return something like:

C:\Documents and Files\user_name\Pictures\My File.jpg

instead of just:

My File.jpg

This is easily handled by File.basename, which strips out everything before the filename.

def sanitize_filename(file_name)
  # get only the filename, not the whole path (from IE)
  just_filename = File.basename(file_name) 
  # replace all none alphanumeric, underscore or perioids
  # with underscore
  just_filename.sub(/[^\w\.\-]/,'_') 
end


Deleting an existing File:

If you want to delete any existing file then its simple and need to write following code:

  def cleanup
    File.delete("#{RAILS_ROOT}/dirname/#{@filename}") 
            if File.exist?("#{RAILS_ROOT}/dirname/#{@filename}")
  end


For a complete detail on File object, you need to go through Ruby Reference Manual.
  • 大小: 12.3 KB
分享到:
评论
1 楼 fming09 2009-12-14  
大哥能不能给份demo啊

相关推荐

    rails 2.3 chm文档 ,官方最新版

    rails 2.3 chm文档 官方最新版

    rails 文件上传

    本篇文章将深入探讨Rails中的文件上传机制,并结合给定的“rails 文件上传”主题,提供关于如何在Rails应用中实现文件上传的详细知识。 1. **ActionDispatch::Http::UploadedFile**: 当用户通过表单上传文件时,...

    Rails中上传文件保存中文文件名乱码

    在Rails框架中处理文件上传时,经常会遇到一个问题,那就是当用户尝试上传包含中文名称的文件时,文件名可能会出现乱码。这个问题主要是由于字符编码不兼容导致的。Rails默认使用UTF-8编码,但文件系统或者某些外部...

    railsbrain网站的rails2.3文档(bug修复版)

    Railsbrain是一个专注于Rails框架的在线资源平台,而这个“railsbrain网站的rails2.3文档(bug修复版)”显然是一份针对Rails 2.3版本的更新文档,旨在修复用户在浏览和交互过程中遇到的问题。Rails是Ruby编程语言的...

    ruby on rails 2.3.5 api html版

    10. **插件和Gem**:Rails的生态系统中,Gem是第三方库的主要形式,它们提供了额外的功能,如Devise用于身份验证,CanCanCan用于授权,Paperclip或Carrierwave处理文件上传等。 11. **部署**:了解如何将Rails应用...

    rails 3.2 API

    Rails 3.2 API 是一个重要的开发资源,主要用于Ruby on Rails框架的开发。Rails是基于Ruby语言的一个开源Web应用程序框架,遵循MVC(Model-View-Controller)架构模式,广泛应用于构建动态网站和Web应用程序。Rails ...

    rails2.3.2

    这个压缩包很可能包含了 Rails 框架的源代码和其他相关文件,方便开发者进行下载、学习和使用。 标签 "rails ruby" 明确指出这个话题涉及到 Ruby 语言和 Rails 框架。Ruby 是一种面向对象的、动态类型的编程语言,...

    jquery-fileupload-rails, 用于 Rails的jQuery文件上传集成.zip

    jquery-fileupload-rails, 用于 Rails的jQuery文件上传集成 Rails 文件上传jQuery-File-Plugin 是一个文件上传插件,由的Tschan 。 jQuery文件上传功能多文件选择。drag&拖放支持。进度栏和jQuery预览图像。 支持...

    Ruby on Rails 2.3 Guide.chm

    Ruby on Rails Guide:是rails官方教程,本人为了大家学习查阅的方便,制成chm格式。就如同java doc的chm格式一样方便。

    rails guides 2.3 CHM版

    rails guides的CHM版本,这个向导的版本是2.3

    Rails 学习资料

    标题“Rails学习资料”表明这是一份关于Rails框架的学习资源,可能包含教程、示例代码、最佳实践等内容,适合初学者和有一定经验的开发者。描述中的“仅仅三分,就可以帮助你搭好框架”,暗示这份资料可能包含快速...

    Rails 101 入门电子书

    ### Rails 101 入门电子书知识点详解 #### 一、简介 ...通过以上内容的学习,初学者可以全面掌握Ruby on Rails的基础知识,包括环境搭建、基本操作、高级特性等,为后续更深入的学习打下坚实的基础。

    升级版本后Rails的文件上传

    在Ruby on Rails框架中,文件上传是一个常见的需求,特别是在应用的升级过程中,处理文件上传的策略可能会有所变化。Rails提供了多种处理文件上传的方法,包括直接存储到本地文件系统、使用云存储服务(如Amazon S3...

    常用RAILS学习网站

    收集了常用RAILS学习的网址 收集了常用RAILS学习的网址

    rails学习教程

    本“rails学习教程”PDF文档将涵盖以上所有内容,通过详尽的实例和解释,帮助你从新手到熟手,全面掌握Rails开发。无论是想从事Web开发职业,还是想要提升个人项目开发能力,这都是一份不可多得的学习资料。

    Rails101_by_rails4.0

    《Rails101_by_rails4.0》是一本专注于Rails 4.0.0版本和Ruby 2.0.0版本的自学教程书籍,它定位于中文读者,旨在成为学习Rails框架的参考教材。Rails(Ruby on Rails)是一个采用Ruby语言编写的开源Web应用框架,它...

    rails查询学习笔记

    以上内容只是Rails查询学习笔记中可能涵盖的部分主题,具体笔记内容还需要参考博文链接或实际文件内容来获取详细信息。学习和理解这些知识点,对于任何Rails开发者来说,都能极大地提升他们在数据库操作上的效率和...

    关于rails 3.1 cucumber-rails 1.2.0

    这些支持文件增强了Cucumber-Rails的灵活性和可定制性。 结合Rails 3.1的Asset Pipeline和Cucumber-Rails 1.2.0,开发者能够构建出一个既高效又健壮的Web应用程序。Asset Pipeline优化了前端资源的处理,Cucumber-...

Global site tag (gtag.js) - Google Analytics