用Sinatra上传文件 [英] File upload with Sinatra

查看:126
本文介绍了用Sinatra上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Sinatra上传文件。我有代码这里,但我得到错误方法file_hash不存在(见/ lib / mvc / helpers / helpers.rb)。



这是怎么回事?是否有一些依赖我缺少。

解决方案

http://www.ruby-forum.com/topic/193036 =noreferrer>这个帖子。



包括在这里以防万一链接永远消失:

  post'/ upload'do 
除非params [:file]&&
(tmpfile = params [:file] [:tempfile])&&
(name = params [:file] [:filename])
@error =没有选择文件
返回haml(:upload)
结束
STDERR。放置上传文件,原名#{name.inspect}
而blk = tmpfile.read(65536)
#在这里,您将它写到它的最终位置
STDERR.puts blk。检查
结束
上传完成
结束

视图看起来像这样。这使用HAML,但重要的是不要忘记在你的表单元素中设置enctype,否则你只会得到文件名而不是对象:

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


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.

解决方案

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"}

这篇关于用Sinatra上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆