Ruby 上传文件

[code="ruby"]

def get_image_body_data data={}

    request_body=[]

     request_body<<%Q{Content-Type:multipart/form-data,boundary=---AaB03x}<<"\r\n" 


    splict_label="---AaB03x"  

    request_body<<splict_label.chomp<<"\r\n" 

     request_body<<"Content-Disposition: form-data; name=\"status\"\r\n\r\n"   



     request_body<<%Q{#{data.fetch(:status,"")}}.chomp<<"\r\n"    

     request_body<<splict_label.chomp<<"\r\n"     



    request_body<<%Q{content-disposition: form-data; name="photo"; filename="saddam.jpg"}.chomp<<"\r\n"      



    request_body<<%Q{Content-Type: image/jpeg}.chomp<<"\r\n\r\n"        



    request_body<< data.delete(:photo)<<"\r\n"    



     request_body<<splict_label.chomp<<"\r\n" 

     request_body<<"Content-Disposition: form-data;name=\"source\"\r\n\r\n"

     request_body<<"#{FanfouModule::SOURCE}\r\n"



    request_body<<("---AaB03x--".chomp)<<"\r\n"

     request_body.to_s



end

[/code]

[code="ruby"]

def do_upload_image data

url="http://127.0.0.1:3000/" 



url = URI.parse(url)

req = Net::HTTP::Post.new(url.path)

req.basic_auth @username,@password  
 req.set_content_type("multipart/form-data")  
# req.body=data.to_s


res = Net::HTTP.new(url.host, url.port).start {|http|   
    http.request(req,data.to_s) }

case res 

when Net::HTTPSuccess, Net::HTTPRedirection
      puts res.body 
    true                

else 
      puts res.body
      false  

end 
res    

end

[/code]

[code="java"]
def packImage image_file_uri
a=[]
File.open(image_file_uri) {|file|

file.each_line{|ch|
a<<ch
}
}
b=[]
b<<(a.to_s)
b.pack('m')
end

[/code]
[code="ruby"]
def upload_image photo,status=""

   photo 为文件路径名称. packImage的方式就是将文件用Base64编码, 
   photo=packImage(photo)


   data = get_image_body_data({:photo=>photo,:status=>status,:source=>SOURCE})

   do_upload_image  data

 end 

[/code]

我每次执行 upload_image的时候,后台都无法获取 photo这个参数,我不知道是什么原因,
或许是自己对Http的协议不是太了解, 希望有人能给我一些指点

3个回答

看了你的代码,从这句【FanfouModule::SOURCE】看出你是在做饭否上传图片的api,去饭否api文档看了下,这样基本满足你的要求了,不过还有个小问题就是source和status这两个可选参数没有加进去,楼主自己修改吧。

[code="ruby"]
require'net/http'
require'uri'
class Multipart
def initialize( file_names )
@file_names = file_names
end
def post( to_url,user,password)
boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'
parts = []
streams = []
@file_names.each do |param_name, filepath|
pos = filepath.rindex('/')
filename = filepath[pos + 1, filepath.length - pos]
parts << StringPart.new ( "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + param_name.to_s + "\"; filename=\"" + filename + "\"\r\n" +
"Content-Type: video/x-msvideo\r\n\r\n")
stream = File.open(filepath, "rb")
streams << stream
parts << StreamPart.new (stream, File.size(filepath))
end
parts << StringPart.new ( "\r\n--" + boundary + "--\r\n" )
post_stream = MultipartStream.new( parts )
url = URI.parse( to_url )
req = Net::HTTP::Post.new(url.path)
req.basic_auth user,password
req.content_length = post_stream.size
req.content_type = 'multipart/form-data; boundary=' + boundary
req.body_stream = post_stream
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
streams.each do |stream|
stream.close();
end
res
end
end
class StreamPart
def initialize( stream, size )
@stream, @size = stream, size
end
def size
@size
end
def read ( offset, how_much )
@stream.read ( how_much )
end
end
class StringPart
def initialize ( str )
@str = str
end
def size
@str.length
end
def read ( offset, how_much )
@str[offset, how_much]
end
end
class MultipartStream
def initialize( parts )
@parts = parts
@part_no = 0;
@part_offset = 0;
end
def size
total = 0
@parts.each do |part|
total += part.size
end
total
end
def read ( how_much )
if @part_no >= @parts.size
return nil;
end
how_much_current_part = @parts[@part_no].size - @part_offset
how_much_current_part = if how_much_current_part > how_much
how_much
else
how_much_current_part
end
how_much_next_part = how_much - how_much_current_part
current_part = @parts[@part_no].read(@part_offset, how_much_current_part )
if how_much_next_part > 0
@part_no += 1
@part_offset = 0
next_part = read ( how_much_next_part )
current_part + if next_part
next_part
else
''
end
else
@part_offset += how_much_current_part
current_part
end
end
end
#This is a test~~
url='http://api.fanfou.com/photos/upload.xml'
photo_path=Dir.pwd+'/a.gif'#你要上传的图片的路径
client=Multipart.new(:photo=>photo_path)
client.post(url,'username','password')

[/code]

如果你不是在windows平台,可以试试用curl
[code="java"]
def upload(photo)
curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost
end
[/code]

还有,或许这个会对你有帮助,Good Luck~~

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问