我在一个受基本身份验证保护的外部服务(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文件和表单的内容。但没有任何处理。我做错了什么?
提前致谢。
答案 0 :(得分: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;你只需几行代码即可上传文件。