Skip to content

Instantly share code, notes, and snippets.

@nisovin
Created April 15, 2023 23:33
Show Gist options
  • Save nisovin/8122be6a80df27751f3717bbfbb1a4eb to your computer and use it in GitHub Desktop.
Save nisovin/8122be6a80df27751f3717bbfbb1a4eb to your computer and use it in GitHub Desktop.
extends HTTPRequest
class_name HTTPFilePost
func post_file(url: String, field_name: String, file_name: String, file_path: String, post_fields: Dictionary = {}, content_type: String = "", custom_headers: Array = [], verify_ssl: bool = true):
var file = File.new()
file.open(file_path)
var content = file.get_buffer(file.get_len())
file.close()
post_data_as_file(url, field_name, file_name, content, post_fields, content_type, custom_headers, verify_ssl)
func post_data_as_file(url: String, field_name: String, file_name: String, data, post_fields: Dictionary = {}, content_type: String = "", custom_headers: Array = [], verify_ssl: bool = true):
randomize()
var boundary = "---------------------------" + str(randi()) + str(randi())
custom_headers.append("content-type: multipart/formdata; boundary=" + boundary)
var body1 = "\r\n\r\n" + boundary + "\r\n"
for key in post_fields:
body1 += "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + post_fields[key] + "\r\n"
body1 += "Content-Disposition: form-data; name=\"" + field_name + "\"; filename=\"" + file_name + "\"\r\nContent-Type: "
if content_type != "":
body1 += content_type
elif data is String:
body1 += "text/plain"
else:
body1 += "application/octet-stream"
body1 += "\r\n\r\n"
var body2 = "\r\n" + boundary + "--"
var post_content
if data is String:
post_content = (body1 + data + body2).to_utf8()
elif data is PoolByteArray:
post_content = body1.to_utf8() + data + body2.to_utf8()
else:
assert(false)
return false
request_raw(url, custom_headers, verify_ssl, HTTPClient.METHOD_POST, post_content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment