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

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

问题描述

我正在尝试使用 Sinatra 上传文件.我有代码 here,但我收到错误方法 file_hash 不存在"(见/lib/mvc/helpers/helpers.rb).

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.

推荐答案

我对 这个话题.

将其包含在此处以防链接消失:

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

那么您的视图将如下所示.这使用了 HAML,但重要的部分是不要忘记在表单元素中设置 enctype,否则你只会得到文件名而不是对象:

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天全站免登陆