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)

別の方法として、Net::HTTP の低レベルの欠点を取り除く他の http ライブラリを検討することもできます。チェックアウトファラデー; わずか数行のコードでファイルのアップロードを実行できます。

于 2012-09-26T12:41:16.363 に答える