Why can not I send an image to the server?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By IuryBorges1993
extends Panel

var toogle;

# Called when the node enters the scene tree for the first time.
func _ready():
	
	toogle=false;
	t()
	
	
	pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass

func t():
	var http=HTTPClient.new()
	http.connect_to_host("http://localhost",80)
	var r=PoolByteArray()
	r.append("----WebKitFormBoundaryePkpFF7tjBAqx29L\n")
	r.append("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"c.png\"\n")
	r.append("Content-Type: image/png\n")
	r.append("\n")
	var file = File.new()
	file.open("res://img/c.png", file.READ)
	var content = file.get_buffer(file.get_len())
	file.close()
	r.append_array(content)
	r.append("----WebKitFormBoundaryePkpFF7tjBAqx29L")
	var headers=[
 	  "Content-Length: "+String(content.size()),
	   "Content-Type: multipart/form-data,  boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L"
	]
	var result = http.request_raw(HTTPClient.METHOD_POST,"/teste/teste.php",headers,r)
	while (http.get_status() == HTTPClient.STATUS_REQUESTING):
		http.poll()
		OS.delay_msec(500)

	if http.get_status() != HTTPClient.STATUS_BODY and http.get_status() != HTTPClient.STATUS_CONNECTED:
		return

	if !http.has_response():
 	   return
	
	var rb=PoolByteArray()
	
	while(http.get_status()==HTTPClient.STATUS_BODY):
		http.poll()
		var chunk = http.read_response_body_chunk() # Get a chunk
		if chunk.size()==0:
			OS.delay_usec(1000)
		
		rb = rb + chunk # Append to read buffer
	
		var text = rb.get_string_from_utf8()
		print(text)

	pass


func _on_TextureButton_pressed():
	if toogle:
		$ConteinerMenuH/menuH.visible=false;
		toogle=false;
	else:
		$ConteinerMenuH/menuH.visible=true;
		toogle=true;
	
	
	pass # Replace with function body.


func _on_http_request_completed(result, response_code, headers, body):
	
	print(body.get_string_from_utf8());
	pass # Replace with function body.

Did you manage to resolve this?

namathos | 2020-06-19 14:41

:bust_in_silhouette: Reply From: chris.brkt

I can see that you have some syntax issues.

1- If your boundary is “B0unDarY321”, the body should start with “–” + boundary and ends with “–” + boundary + “–”

So in your case, you have “----WebKitFormBoundaryePkpFF7tjBAqx29L” which contains already for dashes, in the body should be

“------WebKitFormBoundaryePkpFF7tjBAqx29L”
and at the end
“------WebKitFormBoundaryePkpFF7tjBAqx29L–”

You can reduce the boundary to make it less confusing for you.

2- I can see a typo in the content-type header:

Instead of “Content-Type: multipart/form-data, boundary=…”
try
“Content-Type: multipart/form-data; boundary=…”

3- You should go on a new line after the content so put and extra r.append(“\n”) after adding content and before the boundary