手把手学习Rails 文件上传(支持Rails2.3)
来源:互联网 发布:广广西电网络收视费 编辑:程序博客网 时间:2024/04/29 21:55
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.
- 手把手学习Rails 文件上传(支持Rails2.3)
- rails2.3 kindeditor实现本地上传图片
- rails上传文件
- rails 文件上传
- 手把手教Jsp上传文件
- 使用Rails实现文件上传
- 使用Rails实现文件上传
- rails2
- 文件上传,支持批量上传
- CppCMS支持文件上传
- rails上传文件_非插件
- Rails文件上传-无插件方式
- Ruby on Rails服务器文件上传
- rails开发利器:rails2.3.8 如何配置发送邮件
- 让UpdatePanel支持上传文件
- Servlet 3.0文件上传支持
- spring 支持文件上传配置
- java 文件上传支持断点续传
- BI跟报表一样吗?
- native 调用 java 类中的一个静态方法
- asp.net 导出数据源到Excel模版文件
- C#的参数传递,一道面试题
- shangXueChang Mashibing shs 整合项目创建由零开始
- 手把手学习Rails 文件上传(支持Rails2.3)
- linux sig
- Js获取屏幕高度和宽度
- android surfaceflinger研究----Surface机制
- centos6下编译webkit时依赖库atk/glib的安装
- Delphi开发WebService给ASP.NET调用
- Bos平台修改发布业务单元的jdk版本
- 用 Qt 中的 QDomDocument类 处理 XML 文件(下)
- WriteFile()写串口 .