如何正确格式化Http multipart / form-data请求以将文件上传到服务器

时间:2016-05-25 19:30:15

标签: ruby http file-upload tcp http-headers

我有一个接收文件的简单节点js服务器/应用程序。我已经尝试使用CURL上传jpeg文件并且工作得很好。我尝试使用postman也可以正常工作。但是当我尝试通过Tcp套接字上传带有简单ruby脚本的jpeg时它不起作用。请求是服务器收到但没有文件对象。在节点js服务器路由中,我正在调试请求,如console.log(request.body);,这将返回undefined。使用Curl和postman我得到一个正确的请求对象(文件)。这似乎我在ruby脚本中的http请求格式不正确,有人能指出我在这里做错了什么吗?提前谢谢。这是我的ruby脚本

require 'socket'   

host = "127.0.0.1"
port = 8080

client = TCPSocket.open(host, port)

client.write("POST /api/binary HTTP/1.1\r\n")
client.write("Host: 127.0.0.1\r\n")
client.write ("Accept: */* \r\n")
client.write ("Content-Type: multipart/form-data; boundary=AaB03x\r\n")
client.write ("\r\n")
client.write("AaB03x"+ "\n" + "Content-Disposition: form-data; name='datafile'; filename='cam.jpg' \n Content-Type: image/jpeg \r\n")

data = File.open("./dom.jpg", "rb") {|io| io.read}
client.write (data)
client.write("boundary=AaB03x\r\n")
client.write ("\r\n") 
client.close

从邮递员生成的代码snipet

POST /api/binary HTTP/1.1
Host: myapp.herokuapp.com
Cache-Control: no-cache
Postman-Token: c15a79a2-3a4b-0555-a876-9032afeab5de
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=""; filename=""
Content-Type: 


----WebKitFormBoundary7MA4YWxkTrZu0gW

1 个答案:

答案 0 :(得分:0)

我没有通过Content-Length: length最终版本是有效的。

require 'socket'   

host = "myapp.herokuapp.com"
port = 80

client = TCPSocket.open(host, port)

client.write("POST /api/binary HTTP/1.1\r\n")
client.write("Host: #{host}\r\n")
client.write ("Accept: */*\r\n")
client.write ("Content-Type: multipart/form-data; boundary=AaB03x\r\n")

body = "--AaB03x\r\n"
body << "Content-Disposition: form-data; name='datafile'; filename='cam.jpg'\r\n"

body << "Content-Type: image/jpeg\r\n"
body << "\r\n"
data = File.open("./pic.jpg", "rb") {|io| io.read}

body << data
body << "\r\n"

body << "--AaB03x--\r\n"

client.print "Content-Length: #{body.bytesize}\r\n"

client.print "\r\n"

client.print body

client.close