Proper syntax for multipart/form-data using Godot4

I tested this with a local server. I have not checked if the file is uploaded correctly or not. I’m also not sure how to send it as a binary encoding so I’m using a base64 one.

func send_image() -> void:
	# Create some random bytes to generate our boundary value
	var crypto = Crypto.new()
	var random_bytes = crypto.generate_random_bytes(16)
	var boundary = '--GODOT%s' % random_bytes.hex_encode()
	
	# Setup the header Content-Type with our bundary
	var headers = [
		'Content-Type: multipart/form-data;boundary=%s' % boundary
	]

	# Load the image and get the png buffer
	var image = load("res://letter.png").get_image() as Image
	var buffer = image.save_png_to_buffer()

	# Create our body
	var body = PackedStringArray()
	body.push_back("--{{boundary}}")
	body.push_back('Content-Disposition: form-data; name="api_key"')
	body.push_back('')
	body.push_back("MY_API_KEY") # The API key you have
	body.push_back("--{{boundary}}")
	body.push_back('Content-Disposition: form-data; name="image"; filename="my_image.png"')
	body.push_back('Content-Type: image/png')
	body.push_back('Content-Transfer-Encoding: base64') # Encode is base64
	body.push_back('')
	body.push_back(Marshalls.raw_to_base64(buffer)) # Convert the buffer to a base64 String
	body.push_back("--{{boundary}}--")

	# Finally, join the body with CRLF and insert our boundary
	var final_string = "\r\n".join(body).format({"boundary": boundary}, "{{_}}") 

	http_request.request('http://localhost:5173/upload', headers, HTTPClient.METHOD_POST, final_string)

HTTP request body uses CRLF (the \r\n part) to separate the lines.

Each field has this structure:

  • --boundary
  • Header of that field (Content-Disposition, Content-Type,…)
  • Empty line
  • The content of the field

The body ends with --boundary-- (notice the last -- characters)

The format is kinda explained here POST - HTTP | MDN

1 Like