2012-09-26 75 views
1

我在基本身份驗證保護的外部服務(someurl.com/xmlimport.html)上獲得了以下表單。通過Ruby發佈XML文件

<html> 
<head><title>Upload</title></head> 
<body> 
<h1>Upload</h1> 
<h2>XML Upload</h2> 
<!--<form action="/cgi-bin/xmlimport.pl" method="post" accept-charset="UTF-8" enctype="multipart/form-data">--> 
<form action="/cgi-bin/xmlimport.pl" method="post" enctype="multipart/form-data"> 
Datei: <input name="dateiname" type="file" size="100" accept="text/*"> 
<input type="submit" value="Absenden"/> 
</form> 
</body> 
</html> 

我想通過ruby發佈xml文件。這是我到目前爲止:

require "net/http" 
require "uri" 

uri = URI.parse('http://someurl.com/xmlimport.html') 
file = "upload.xml" 


post_body = [] 
post_body << "Content-Disposition: form-data; name='datafile'; filename='#{File.basename(file)}'rn" 
post_body << "Content-Type: text/plainrn" 
post_body << "rn" 
post_body << File.read(file) 


puts post_body 

http = Net::HTTP.new(uri.host, uri.port) 
request = Net::HTTP::Post.new(uri.request_uri) 
request.basic_auth "user", "pass" 
request.body = post_body.join 
request["Content-Type"] = "multipart/form-data" 

resp = http.request(request) 

puts resp.body 

響應是我的xml文件和窗體的內容。但沒有任何處理。我究竟做錯了什麼?

在此先感謝。

回答

2

Ruby Inside's Net::HTTP Cheat Sheet上有很好的例子,包括文件上傳。看起來你錯過了文件邊界。他們的例子:

require "net/http" 
require "uri" 

# Token used to terminate the file in the post body. Make sure it is not 
# present in the file you're uploading. 
BOUNDARY = "AaB03x" 

uri = URI.parse("http://something.com/uploads") 
file = "/path/to/your/testfile.txt" 

post_body = [] 
post_body << "--#{BOUNDARY}rn" 
post_body << "Content-Disposition: form-data; name="datafile"; filename="#{File.basename(file)}"rn" 
post_body << "Content-Type: text/plainrn" 
post_body << "rn" 
post_body << File.read(file) 
post_body << "rn--#{BOUNDARY}--rn" 

http = Net::HTTP.new(uri.host, uri.port) 
request = Net::HTTP::Post.new(uri.request_uri) 
request.body = post_body.join 
request["Content-Type"] = "multipart/form-data, boundary=#{BOUNDARY}" 

http.request(request) 

作爲一種替代方案,你可以考慮其他的http庫,它提取出Net :: HTTP的底層文件。結帳faraday;只需幾行代碼即可完成文件上傳。