1

我在受基本身份验证保护的外部服务(someurl.com/xmlimport.html)上获得了以下表格。

<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 文件和表单的内容。但没有任何处理。我究竟做错了什么?

提前致谢。

4

1 回答 1

2

Ruby Inside 的 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 的低级垃圾。结帐法拉第;您只需几行代码即可完成文件上传。

于 2012-09-26T12:41:16.363 回答