繁体   English   中英

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

[英]How to properly format Http multipart/form-data request to upload file to the server

我有一个简单的节点js服务器/应用程序,可以接收文件。 我已经尝试过使用CURL上传jpeg文件并且工作正常。我曾尝试过邮递员也可以正常工作。但是当我尝试通过Tcp套接字使用简单的ruby脚本上传jpeg时,它不起作用。服务器收到了请求,但是没有文件对象。在Node js服务器路由中,我正在调试请求,例如console.log(request.body); 这将返回undefined 通过Curl和邮递员,我得到了一个正确的请求对象(文件)。这似乎是我在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

从邮递员生成的代码片段

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

我没有传递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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM