FormAttachement
Back to ListDescription: Create File Part for multipart/formdata API request
FileMaker Prototype:
Set Variable [$res; ACF_Run("FormAttachement"; string_path; string_Name; string_Boundary; bool_b64)]
Category: REST API
Dependencies
- GetExtentionFromPath: Retrieve the file type (extention) from a filename or a full path. NOTE: put
USE bootstrap;below the package header instead of copying the code for GetExtentionFromPath - GetNameFromPath: Retrieve filename part from a full path
The FormAttachement Function builds a Filepart in Multipart/form-data request to an external API.
The last parameter, b64, is set to true if you want the content of the file base64 encoded.
Function source:
function FormAttachement (string path, string Name, string Boundary, bool b64 )
if ( path == "" ) then
return "";
end if
string fn = GetNameFromPath(path);
string ft = lower(GetExtentionFromPath(path));
string ctype, base64;
string crlf = "\r\n";
case
:(ft == "png")
ctype = "image";
:(ft == "jpg" || ft == "jpeg")
ctype = "image";
ft = "jpeg";
default
ctype = "image"; // Any other should be branched above
end case
ctype = ctype+"/"+ft;
string v = Boundary;
string file_content;
v += format ('Content-Disposition: form-data; name="%s"; filename="%s"', Name, fn) + crlf;
v += "Content-Type: "+ctype+crlf;
if ( b64 ) then
v += "Content-Transfer-Encoding: base64"+crlf;
end if
v += crlf;
// Different paths for Mac and Windows
if ( isMac ) then
if ( left ( path, 8) != "/Volumes" && left ( path, 6) != "/Users" && left (path,1) == "/") then
path = "/Volumes"+path; // Paths lack /Volumes as start... - like "/Macintosh HD...."
end if
end if
// Verify that the file exists.
if ( ! file_exists ( path ) ) then
throw format ("ERROR: The Attached file '%s' at the path '%s' does not exists", fn, path );
end if
// Retrieve the binary content
int x = open (path, "rb" );
file_content = read (x);
close (x);
if ( b64 ) then
base64 = BASE64_ENCODE (file_content);
return v + base64+crlf;
else
return v + file_content+crlf;
end if
end
Example
string url = "https://api.openai.com/v1/images/edits";
// format the post data as multipart form data
string vb1 = "--------------------WebKitFormBoundaryvaBIACFqQXnhryXmJxO";
string vb2 = "--" + vb1 + "\r\n";
string vb3 = "--" + vb1 + "--\r\n";
string APIkey = ExecuteSQL ("SELECT AI_APIKey FROM Preferences");
string hdrs = format ( "Content-Type: multipart/form-data; boundary=%s",vb1 )+
"\nAuthorization: Bearer "+APIkey;
string postData =
FormAttachement (imagePath, "image", vb2, false ) +
FormAttachement (maskpath, "mask", vb2, false ) +
FormField ( vb2, "model", "dall-e-2") +
FormField ( vb2, "prompt", "Colorize this image") +
FormField ( vb2, "size", "1024x1024") +
FormField ( vb2, "n", "1") +
FormField ( vb2, "response_format", "b64_json") + vb3;
string respons = HTTP_POST ( url, postdata, hdrs); 