代码之家  ›  专栏  ›  技术社区  ›  Ethan Turkeltaub

使用Sinatra上传文件

  •  16
  • Ethan Turkeltaub  · 技术社区  · 16 年前

    我试图能够上传文件与辛纳特拉。我有密码 here ,但出现错误“method file\u hash does not exist”(请参阅/lib/mvc/helpers/helpers.rb)。

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

    3 回复  |  直到 13 年前
        1
  •  31
  •   Jeremy Mullin    15 年前

    this thread .

    包括在这里以防链接消失:

    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,但重要的是不要忘记在form元素中设置enctype,否则只会得到文件名而不是对象:

    %form{:action=>"/upload",:method=>"post"   ,:enctype=>"multipart/form-data"}
      %input{:type=>"file",:name=>"file"}
      %input{:type=>"submit",:value=>"Upload"}
    
        2
  •  23
  •   Martin Tournoij ravi.zombie    11 年前
    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
  •  4
  •   Waheed    7 年前

    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
    

    原件在 https://github.com/tbuehlmann/sinatra-fileupload 但是我的环境有一些配置问题。别忘了加上 enctype="multipart/form-data" method="POST" 在上传表格上。