- 浏览: 2075962 次
- 性别:
- 来自: NYC
文章分类
- 全部博客 (628)
- Linux (53)
- RubyOnRails (294)
- HTML (8)
- 手册指南 (5)
- Mysql (14)
- PHP (3)
- Rails 汇总 (13)
- 读书 (22)
- plugin 插件介绍与应用 (12)
- Flex (2)
- Ruby技巧 (7)
- Gem包介绍 (1)
- javascript Jquery ext prototype (21)
- IT生活 (6)
- 小工具 (4)
- PHP 部署 drupal (1)
- javascript Jquery sort plugin 插件 (2)
- iphone siri ios (1)
- Ruby On Rails (106)
- 编程概念 (1)
- Unit Test (4)
- Ruby 1.9 (24)
- rake (1)
- Postgresql (6)
- ruby (5)
- respond_to? (1)
- method_missing (1)
- git (8)
- Rspec (1)
- ios (1)
- jquery (1)
- Sinatra (1)
最新评论
-
dadadada2x:
user模型里加上 protected def email ...
流行的权限管理 gem devise的定制 -
Sev7en_jun:
shrekting 写道var pattern = /^(0| ...
强悍的ip格式 正则表达式验证 -
jiasanshou:
好文章!!!
RPM包rpmbuild SPEC文件深度说明 -
寻得乐中乐:
link_to其实就是个a标签,使用css控制,添加一个参数: ...
Rails在link_to中加参数 -
aiafei0001:
完全看不懂,不知所然.能表达清楚一点?
"$ is not defined" 的问题怎么办
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.
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.
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.
Now we will create a method called save in data_file.rb model file. This method will be called by the application controller.
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:
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'".
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:
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.
Deleting an existing File:
If you want to delete any existing file then its simple and need to write following code:
For a complete detail on File object, you need to go through Ruby Reference Manual.
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.
发表评论
-
Destroying a Postgres DB on Heroku
2013-04-24 10:58 935heroku pg:reset DATABASE -
VIM ctags setup ack
2012-04-17 22:13 3259reference ctags --extra=+f --e ... -
alias_method_chain方法在3.1以后的替代使用方式
2012-02-04 02:14 3295alias_method_chain() 是rails里的一个 ... -
一些快速解决的问题
2012-01-19 12:35 1472问题如下: 引用Could not open library ... -
API service 安全问题
2011-12-04 08:47 1386这是一个长期关注的课题 rest api Service的 ... -
Module方法调用好不好
2011-11-20 01:58 1349以前说,用module给class加singleton方法,和 ... -
一个ajax和rails交互的例子
2011-11-19 01:53 1908首先,这里用了一个,query信息解析的包,如下 https: ... -
Rails 返回hash给javascript
2011-11-19 01:43 2277这是一个特别的,不太正统的需求, 因为,大部分时候,ajax的 ... -
关于Rubymine
2011-11-18 23:21 2267开个帖子收集有关使用上的问题 前一段时间,看到半价就买了。想 ... -
ruby中和javascript中,动态方法的创建
2011-11-18 21:01 1241class Klass def hello(*args) ... -
textmate快捷键 汇总
2011-11-16 07:20 8147TextMate 列编辑模式 按住 Alt 键,用鼠标选择要 ... -
Ruby面试系列六,面试继续面试
2011-11-15 05:55 2025刚才受到打击了,充分报漏了自己基础不扎实,不肯向虎炮等兄弟学习 ... -
说说sharding
2011-11-13 00:53 1492这个东西一面试就有人 ... -
rails面试碎碎念
2011-11-12 23:51 1946面试继续面试 又有问ru ... -
最通常的git push reject 和non-fast forward是因为
2011-11-12 23:29 17216git push To git@github.com:use ... -
Rails 自身的many to many关系 self has_many
2011-11-12 01:43 2738简单点的 #注意外键在person上people: id ... -
Rails 3下的 in place editor edit in place
2011-11-12 01:20 946第一个版本 http://code.google.com/p ... -
Heroku 的诡异问题集合
2011-11-11 07:22 1697开个Post记录,在用heroku过程中的一些诡异问题和要注意 ... -
SCSS 和 SASS 和 HAML 和CoffeeScript
2011-11-07 07:52 12960Asset Pipeline 提供了内建 ... -
Invalid gemspec because of the date format in specification
2011-11-07 02:14 2122又是这个date format的错误。 上次出错忘了,记录下 ...
相关推荐
rails 2.3 chm文档 官方最新版
本篇文章将深入探讨Rails中的文件上传机制,并结合给定的“rails 文件上传”主题,提供关于如何在Rails应用中实现文件上传的详细知识。 1. **ActionDispatch::Http::UploadedFile**: 当用户通过表单上传文件时,...
在Rails框架中处理文件上传时,经常会遇到一个问题,那就是当用户尝试上传包含中文名称的文件时,文件名可能会出现乱码。这个问题主要是由于字符编码不兼容导致的。Rails默认使用UTF-8编码,但文件系统或者某些外部...
Railsbrain是一个专注于Rails框架的在线资源平台,而这个“railsbrain网站的rails2.3文档(bug修复版)”显然是一份针对Rails 2.3版本的更新文档,旨在修复用户在浏览和交互过程中遇到的问题。Rails是Ruby编程语言的...
10. **插件和Gem**:Rails的生态系统中,Gem是第三方库的主要形式,它们提供了额外的功能,如Devise用于身份验证,CanCanCan用于授权,Paperclip或Carrierwave处理文件上传等。 11. **部署**:了解如何将Rails应用...
Rails 3.2 API 是一个重要的开发资源,主要用于Ruby on Rails框架的开发。Rails是基于Ruby语言的一个开源Web应用程序框架,遵循MVC(Model-View-Controller)架构模式,广泛应用于构建动态网站和Web应用程序。Rails ...
这个压缩包很可能包含了 Rails 框架的源代码和其他相关文件,方便开发者进行下载、学习和使用。 标签 "rails ruby" 明确指出这个话题涉及到 Ruby 语言和 Rails 框架。Ruby 是一种面向对象的、动态类型的编程语言,...
jquery-fileupload-rails, 用于 Rails的jQuery文件上传集成 Rails 文件上传jQuery-File-Plugin 是一个文件上传插件,由的Tschan 。 jQuery文件上传功能多文件选择。drag&拖放支持。进度栏和jQuery预览图像。 支持...
Ruby on Rails Guide:是rails官方教程,本人为了大家学习查阅的方便,制成chm格式。就如同java doc的chm格式一样方便。
rails guides的CHM版本,这个向导的版本是2.3
标题“Rails学习资料”表明这是一份关于Rails框架的学习资源,可能包含教程、示例代码、最佳实践等内容,适合初学者和有一定经验的开发者。描述中的“仅仅三分,就可以帮助你搭好框架”,暗示这份资料可能包含快速...
### Rails 101 入门电子书知识点详解 #### 一、简介 ...通过以上内容的学习,初学者可以全面掌握Ruby on Rails的基础知识,包括环境搭建、基本操作、高级特性等,为后续更深入的学习打下坚实的基础。
在Ruby on Rails框架中,文件上传是一个常见的需求,特别是在应用的升级过程中,处理文件上传的策略可能会有所变化。Rails提供了多种处理文件上传的方法,包括直接存储到本地文件系统、使用云存储服务(如Amazon S3...
收集了常用RAILS学习的网址 收集了常用RAILS学习的网址
本“rails学习教程”PDF文档将涵盖以上所有内容,通过详尽的实例和解释,帮助你从新手到熟手,全面掌握Rails开发。无论是想从事Web开发职业,还是想要提升个人项目开发能力,这都是一份不可多得的学习资料。
《Rails101_by_rails4.0》是一本专注于Rails 4.0.0版本和Ruby 2.0.0版本的自学教程书籍,它定位于中文读者,旨在成为学习Rails框架的参考教材。Rails(Ruby on Rails)是一个采用Ruby语言编写的开源Web应用框架,它...
以上内容只是Rails查询学习笔记中可能涵盖的部分主题,具体笔记内容还需要参考博文链接或实际文件内容来获取详细信息。学习和理解这些知识点,对于任何Rails开发者来说,都能极大地提升他们在数据库操作上的效率和...
这些支持文件增强了Cucumber-Rails的灵活性和可定制性。 结合Rails 3.1的Asset Pipeline和Cucumber-Rails 1.2.0,开发者能够构建出一个既高效又健壮的Web应用程序。Asset Pipeline优化了前端资源的处理,Cucumber-...