Skip to content

Instantly share code, notes, and snippets.

@FishOfPrey
Last active January 17, 2020 02:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FishOfPrey/fe7f5ac7cdf7f423c003598e7d6af4df to your computer and use it in GitHub Desktop.
Save FishOfPrey/fe7f5ac7cdf7f423c003598e7d6af4df to your computer and use it in GitHub Desktop.
public virtual class EinsteinVision_HttpBodyPart {
//...
/**
* Write a key-value pair to the form's body for a blob.
*/
public static string WriteBlobBodyParameter(string key, string file64, string filename, string mimeType) {
string contentDisposition = 'Content-Disposition: form-data; name="' + key + '"; filename="'+filename+'"';
string contentDispositionCrLf = contentDisposition + '\r\n';
blob contentDispositionCrLfBlob = blob.valueOf(contentDispositionCrLf);
string contentDispositionCrLf64 = EncodingUtil.base64Encode(contentDispositionCrLfBlob);
string content = SafelyPad(contentDisposition, contentDispositionCrLf64, '\r\n');
string contentTypeHeader = 'Content-Type: ' + mimeType;
string contentTypeCrLf = contentTypeHeader + '\r\n\r\n';
blob contentTypeCrLfBlob = blob.valueOf(contentTypeCrLf);
string contentTypeCrLf64 = EncodingUtil.base64Encode(contentTypeCrLfBlob);
content += SafelyPad(contentTypeHeader, contentTypeCrLf64, '\r\n\r\n');
integer file64Length = file64.length();
String last4Bytes = file64.substring(file64.length()-4,file64.length());
// Avoid padding the file data with spaces, which SafelyPad does
// http://salesforce.stackexchange.com/a/33326/102
EndingType ending = EndingType.None;
if (last4Bytes.endsWith('==')) {
last4Bytes = last4Bytes.substring(0,2) + '0K';
file64 = file64.substring(0,file64.length()-4) + last4Bytes;
ending = EndingType.CrLf;
} else if (last4Bytes.endsWith('=')) {
last4Bytes = last4Bytes.substring(0,3) + 'N';
file64 = file64.substring(0,file64.length()-4) + last4Bytes;
ending = EndingType.Cr;
}
content += file64;
content += WriteBoundary(ending);
return content;
}
/**
* Helper enum indicating how a file's base64 padding was replaced.
*/
public enum EndingType {
Cr,
CrLf,
None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment