Io faccio
così: partial:
Selezionare il file da caricare e premi Salva.
Dimension
e massima: 80Mb
<%= file_field_tag "media[data]", {:id =>
"media_data"}%>
<%= submit_tag 'Salva' %>
model (“Media”):
validates_uniqueness_of :filename,
:on =>:create,
:message => “Un file con quel nome esiste già. Per
sost
ituirlo, cancellare la versione precedente e riprovare.”
controller:
def show
@media = Media.find params[:id]
if @media
send_data @media.data, {:filename => @media.filename,
type => @
media.mimetype}
logger.debug “MediasController#show Sent file
[1]”#{@media.fil
ename}" with size #{@media.data.length}"
else
logger.error “MediasController#show Could not load media
from d
atabase. False ID? params: #{params.inspect}”
flash[:error] = “Impossibile reperire i dati del
file c
on id #{params[:id]}”
end
end
def create
filedata = params[:media][:data]
unless filedata.respond_to?(:local_path)
logger.error “MediasController#create No file in there.
#{filed
ata.inspect}”
flash[:error] = “Impossibile riconoscere il file
carica
to.”
else
content_type = filedata.content_type.chomp
unless MimeTypes.detect{|type| type == content_type}
logger.error “[email protected] Wrong
mimetype "
#{content_type}”"
flash[:error] = "Tipo di file
“#{content_type}
" non riconosciuto. Impossibile caricare file.”
else
@media = Media.new
params[:media
]
@media.podcast_id =
params[:podcast_id]
@media.mimetype = content_type
@media.filename =
filedata.original_filen
ame.gsub(/^.*(\|/)/, ‘’).chomp.downcase.strip.gsub(/[^\w.-]/,’’) #
Sanitiz
e filename by stripping all but final part of filename (IE fix), chop
off trail
ing newlines and whitespace and, finally, convert non alpha-numeric
stuff to "
"
@media.data =
filedata.sysread(fileda
ta.length)
old_logger_level, logger.level = logger.level,
Logger::
ERROR if logger
saved = @media.save
logger.level = old_logger_level if logger
if saved
logger.debug "MediasController#create
SAVE was
ok."
flash[:notice] = “Media inserito con
successo”
else
logger.error “MediasController#create
SAVE FAIL
ED.”
logger.debug [2]“[email protected]
Errors
: #{@media.errors.each{|att, msg| “\n\t#{att}:\t\t#{msg}”}}”
errors = “Impossibile inserire
nuovo med
ia.”
@media.errors.each{|att, msg| errors +=
" #{msg
}
"}
flash[:error] = errors
end
end
end
flash.keep
redirect_to :controller => :podcasts, :action => :edit, :id =>
params[:
podcast_id]
end
migration:
class CreateMedias < ActiveRecord::Migration
def self.up
create_table :medias do |t|
t.column :podcast_id, :integer
t.column :filename, :string
t.column :mimetype, :string
t.column :data, :binary
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
end
def self.down
drop_table :medias
end
end
Il metodo “create” va ripulito di roba che sta molto meglio nel model
e prima di chiudere il progetto farò un po’ di refactoring; trovo
comodo a volte disubbedire alle regole MVC per avere tutto in un
posto
mentre sviluppo.

Ashkey wrote:
Ciao a tutti,
da diverse settimane sto lavorando ad una applicaizone Rails con
ottimi risultati, ma mi trovo a daffrontare un problema per me
totalmente nuovo: devo effettuare un POST HTTP di un file dalla mia
applicazione ad un server remoto e mi chiedevo se c'era qualche
libreria che mi permetta di farlo con codice di alto livello. Una
delle mie esigenze è anche esaminare la response (il tutto
ovviamente
in modo sincrono, l'utente aspetta ;-)
Qualcuno mi sa consigliare?
Grazie in anticipo,
–
“Den som väntar på något gott väntar inte för länge. Den som väntar på någon so
m har gått får vänta länge. Den som har väntat för gott har väntat för länge.”
References
- mailto:/#{@media.filename}\
-
mailto:[email protected]:#{@media.errors.each{|att,msg|