Sinatra and http put

Suppose I want to use curl to host a file in a web service this way

curl -v --location --upload-file file.txt http://localhost:4567/upload/filename

in sinatra i can do:

#!/usr/bin/env ruby

require 'rubygems'
require 'sinatra'

put '/upload/:id' do
   #
   # tbd
   #
end

how can i read the stream file?

more or less i want something like this: http://www.php.net/manual/en/features.file-upload.put-method.php#56985

+5
source share
2 answers

The simplest example is to write it to the personal directory in which the sinatra is running, without checking the existing files ... just dropping them.

#!/usr/bin/env ruby

require 'rubygems'
require 'sinatra'

put '/upload/:id' do
  File.open(params[:id], 'w+') do |file|
    file.write(request.body.read)
  end
end

Alternatively, you can leave part of the file name in the curl command, and it will populate it with the file name for you. Game example:

curl -v --location --upload-file file.txt http://localhost:4567/upload/

will write the file to http: // localhost: 4567 / upload / file.txt

+4
require 'rubygems'
require 'sinatra'
require 'ftools'

put '/upload' do
  tempfile = params['file'][:tempfile]
  filename = params['file'][:filename]
  File.mv(tempfile.path,File.join(File.expand_path(File.dirname(File.dirname(__FILE__))),"public","#{filename}"))
  redirect '/'
end

, , () , temp , . , php- , 1k , , . , .

+2

All Articles