ApexでREST API使用して画像ファイルUpload
public void fileUpload(Attachment attach){
HttpRequest req = new HttpRequest();
Http http = new Http();
HTTPResponse res = new HTTPResponse();
String boundary = '------------' + String.valueOf(DateTime.now().getTime());
String header += '--' + boundary;
header += '\r\n';
header += 'Content-Disposition: form-data; name="attach"; filename="' + attach.name + '"';
header += '\r\n';
header += 'Content-Type: ' + attach.ContentType;
String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
while(headerEncoded.endsWith('=')){
header += ' ';
headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header + ' ' +'\r\n\r\n'));
}
String bodyEncoded = EncodingUtil.base64Encode(attach.Body);
String footor += '\r\n';
footor += '--'+boundary;
footor += '\r\n';
footor += 'Content-Disposition: form-data; name="attachname"';
footor += '\r\n\r\n';
footor += attach.name;
footor += '\r\n';
footor += '--'+boundary+'--';
String footorEncoded = EncodingUtil.base64Encode(Blob.valueOf(footor));
Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
if(last4Bytes.endsWith('='))
{
Blob decoded4Bytes = EncodingUtil.base64Decode(last4Bytes);
HttpRequest tmp = new HttpRequest();
tmp.setBodyAsBlob(decoded4Bytes);
String last4Bytesfootor = tmp.getBody()+footor;
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded.substring(0,bodyEncoded.length()-4)+EncodingUtil.base64Encode(Blob.valueOf(last4Bytesfootor)));
}
else
{
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footorEncoded);
}
req = new HttpRequest();
req.setHeader('Content-Type','multipart/form-data; boundary=' + boundary);
req.setMethod('POST');
req.setEndpoint('https://' + endPoint);
req.setBodyAsBlob(bodyBlob);
req.setTimeout(120000);
http = new Http();
res = http.send(req);
}