Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
2 total  XML / RSS feed 

Upload Image To Database

// Code To Upload an image to a database and then update its contents.

# Create an ew classified and attach an image with it.
def create
  image_types = ["image/jpeg", "image/pjpeg", "image/gif","image/png", "image/x-png"]
  @categories = Category.find(:all)
  @classified = Classified.new(params[:classified])
  @classified.user = session[:user]
  unless params[:classified][:picture].blank?
    if (image_types.include?params[:classified][:picture].content_type.chomp)
      @classified.picture = params[:classified][:picture].read
    else
      @classified.errors.add(:picture,  "Photo doesn't seem to be JPG, GIF, or PNG. please ensure it is a valid image file.")
      render :action => 'new'
      return
    end
  end

  if @classified.save
    redirect_to :action => 'list'
  else 
    render :action => 'new'
  end
end


# Update Method So user can change the image associated with their classified
def update
  image_types = ["image/jpeg", "image/pjpeg", "image/gif", "image/png", "image/x-png"]
  @classified = Classified.find(params[:id])
  @categories = Category.find(:all)
  
  if @classified.update_attributes(params[:classified])
    unless params[:classified][:picture].blank?
      if (image_types.include?params[:classified][:picture].content_type.chomp)
        @classified.picture = params[:classified][:picture].read
      else
        @classified.errors.add(:picture, " doesn't seem to be JPG, GIF, or PNG. please ensure it is a valid image file.")
        render :action => 'edit'
        return
      end
    end
    
    flash[:notice] = 'Classified was successfully updated.'
    redirect_to :action => 'show', :id => @classified
  else
    render :action => 'edit'
  end
end

Johan Sørensen's code to do buffered file uploads in rails

Ruby code to do a buffered file write. Writes chunks of a file to disk from a form post. Ala Johan Sørensen.

File.open("", "wb") do |f|
  while buff = file_field.read(4096)
    f.write(buff)
  end
end
« Newer Snippets
Older Snippets »
2 total  XML / RSS feed