Ruby multi-file upload and write to database

Source: Internet
Author: User
I. Create a table (using Ruby script/generate model attach) and generate a model.
Open dB/migrage/007_create_attaches.rb and change it
Class createattaches <activerecord: Migration
Def self. Up
Create_table: attaches,: force => true do | T |
T. Column: name,: string # attachment name
T. Column: URL,: string # resource path
T. Column: types,: string # attachment type, storage Extension
T. Column: Size,: integer # attachment size
T. Column: last_update,: integer # Update Time
End
End

Def self. Down
Drop_table: attaches
End
End

Execute rake DB: migrate will automatically create the table to the specified database

2. Create an uploadcontroller with the following content (for test purposes only, not for beautification)
Class uploadcontroller <applicationcontroller

Def Index
@ Attach_pages, @ attaches = paginate: attaches,: Order => 'last _ update desc',: per_page => 10
End

Def add
Begin
# Because multiple files are uploaded, loop is required here.
Params [: uploadfile]. Each do | file |
If file. kind_of? (Stringio) | file. exist? (File)
# Call a custom model to upload a file and pass session_id to rename the file to ensure that the file is not named again
Attach = attach. New (file, session. session_id)
Attach. Save
End
End
Rescue
Raise
End
Redirect_to: Action => "Index"
End

End

3. Modify the automatically generated model attach.
Class attach <activerecord: Base

Def initialize (upload, session_id)
File_upload (upload, session_id) # upload the execution File
Super ()
Self. Name = @ name
Self. url = @ URL
Self. types = @ Type
Self. size = @ size
Self. last_update = @ last_update
End

# File Upload
Def file_upload (upload, session_id)
Time_now = time. Now
@ Init_dir = "upload/# {time_no1_strftime ('% Y-% m-% D ')}"

Begin
Fileutils. mkpath (upload_path) unless file. directory? (Upload_path)
If upload. kind_of? (Stringio)
Upload. Rewind
End

Origname = upload. original_filename
Basename = file. basename (origname, ". *") # obtain the file name.
Extname = file. extname (origname). downcase # Get the file extension
Tmpname = "_ 1"
Tmpextname = "_" + time_no1_to_ I .to_s + extname

# Rename
Basename = session_id.nil? ? Digest: md5.hexdigest (basename). to_s: session_id.to_s
Basename = basename. upcase
Endname = basename + tmpextname

# Generating non-repeated file names
While file. exist? (Upload_path (endname ))
Arr = endname. Scan (/[a-zA-Z0-9 _] +/) [0]. Split ("_")
Endname = 2 = arr. Size? (Basename + tmpname + tmpextname): (basename + "_" + arr [1]. succ. to_s + tmpextname)
End

# Writing files to a disk
File. Open (upload_path (endname), "WB") {| f. Write (upload. Read )}

@ Name = origname
@ Url = "// # {@ init_dir}/# {endname }"
@ Type = (extname. Delete ".")
@ Size = upload. Size
@ Last_update = time_no1_to_ I

Rescue
Raise
End

End

# Generating absolute paths
Def upload_path (file = nil)
"# {Rails_root}/public/# {@ init_dir}/# {file. nil? ? '': File }"
End
End

4. Modify views/upload/index. rhtml
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> file upload test </title>
</Head>

<Body>

<! -- Used to display uploaded files -->
<Table border = "1">
<Tr>
<% For column in attach. content_columns %>
<TH> <% = column. human_name %> </Th>
<% End %>
</Tr>

<% For attach in @ attaches %>
<Tr>
<% For column in attach. content_columns %>
<TD> <% = H attach. Send (column. Name) %> </TD>
<% End %>
</Tr>
<% End %>
</Table>

<! -- Name it with [] for Ruby to get a file array -->
<H1> File Upload <% Form_tag ({: Action = >:add}, {: multipart => true}) Do-%>

File Name 1: <% = file_field_tag "uploadfile []"-%> <br/>
File name 2: <% = file_field_tag "uploadfile []"-%> <br/>
File Name 3: <% = file_field_tag "uploadfile []"-%> <br/>
File Name 4: <% = file_field_tag "uploadfile []"-%> <br/>
File name 5: <% = file_field_tag "uploadfile []"-%> <br/>

<% = Submit_tag "File Upload",: disable_with => "File Upload...",: Name => "btnsave",: Id => "btnsave" %>

<% End %>
</Body>
</Html>

CodeThe running effect is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.