Created
July 27, 2011 14:53
-
-
Save yoeun/1109522 to your computer and use it in GitHub Desktop.
Rails 3 file upload (manual)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| = form_for @photo, :html => { :multipart => true } do |f| | |
| .field | |
| = f.label :title | |
| = f.text_field :title | |
| - if !@photo.img_original.nil? and !@photo.img_original.empty? | |
| %img{:src => "/uploads/#{@photo.img_original}", :border => 1, :width => 50, :height => 50 } | |
| .field | |
| = f.label 'New file' | |
| = f.file_field 'file' | |
| .actions | |
| = f.submit 'Save' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class PhotosController < ApplicationController | |
| def create | |
| path = save_file(params[:photo], :file) | |
| @photo = Photo.new(params[:photo]) | |
| @photo.img_original = path | |
| respond_to do |format| | |
| if @photo.save | |
| format.html { redirect_to(photo_path(@photo), :notice => 'Photo was successfully created.') } | |
| format.xml { render :xml => @photo, :status => :created, :location => @photo } | |
| else | |
| format.html { render :action => "new" } | |
| format.xml { render :xml => @photo.errors, :status => :unprocessable_entity } | |
| end | |
| end | |
| end | |
| def save_file(formdata, name) | |
| ufile = formdata[name] | |
| if ufile | |
| path = Rails.root.join('public', 'uploads', ufile.original_filename) | |
| File.open(path, 'wb') do |file| | |
| file.write(ufile.read) | |
| end | |
| formdata.delete name | |
| #return path as string | |
| path.relative_path_from(Rails.root.join('public', 'uploads')).to_s | |
| else | |
| nil | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment