File upload with Sinatra

十年热恋 提交于 2019-11-26 22:40:35

问题


I am trying to be able to upload files with Sinatra. I have the code here, but I'm getting the error "method file_hash does not exist" (see /lib/mvc/helpers/helpers.rb).

What is going on here? Is there some dependency I'm missing.


回答1:


I've had good luck with the example code found on this thread.

Including it here in case the link ever disappears:

post '/upload' do
  unless params[:file] &&
         (tmpfile = params[:file][:tempfile]) &&
         (name = params[:file][:filename])
    @error = "No file selected"
    return haml(:upload)
  end
  STDERR.puts "Uploading file, original name #{name.inspect}"
  while blk = tmpfile.read(65536)
    # here you would write it to its final location
    STDERR.puts blk.inspect
  end
  "Upload complete"
end

Then your view would look like this. This uses HAML, but the important part is not to forget to set the enctype in your form element, otherwise you will just get the filename instead of an object:

%form{:action=>"/upload",:method=>"post"   ,:enctype=>"multipart/form-data"}
  %input{:type=>"file",:name=>"file"}
  %input{:type=>"submit",:value=>"Upload"}



回答2:


include FileUtils::Verbose

get '/upload' do
    erb :upload
end

post '/upload' do
    tempfile = params[:file][:tempfile] 
    filename = params[:file][:filename] 
    cp(tempfile.path, "public/uploads/#{filename}")
    'Yeaaup'
end

__END__

@@upload
<form action='/upload' enctype="multipart/form-data" method='POST'>
    <input name="file" type="file" />
    <input type="submit" value="Upload" />
</form>



回答3:


I found, slightly changed and used this:

if params[:file]
  filename = params[:file][:filename]
  tempfile = params[:file][:tempfile]
  target = "public/files/#{filename}"

  File.open(target, 'wb') {|f| f.write tempfile.read }
end

The original is at https://github.com/tbuehlmann/sinatra-fileupload but have some config issues at my environment. Don't forget to add enctype="multipart/form-data" and method="POST" at the upload form.



来源:https://stackoverflow.com/questions/2686044/file-upload-with-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!