I have tried creating Visualforce Page and Apex that sends the image to Amazon S3 bucket, Though it upload successfully but when i viewed the image using the link from Amazon it shows box instead of the actual image uploaded. See image below
Here is my Visualforce Code that sends the file to apex using javascript:
<input id="logo" name="bsLogo" type="file" />
<button id="submtBtn" onclick="toSubmit()" label="Submit" title="Submit" >Submit</button>
<apex:form id="formId">
<apex:actionFunction name="setParamAF" action="{!apexMethod}" rerender="panelId" status="checkingId" oncomplete="onloadCallback();">
<apex:param name="vBusiLogo" value=""/>
</apex:actionFunction>
</apex:form>
<script>
function toSubmit(){
reader.readAsDataURL(document.getElementById('logo').files[0]);
reader.onload = function(){
var dataURL = reader.result;
setParamAF(dataURL);
};
}
function onl oadCallback(){
alert('uploaded');
}
</script>
The dataURL variable has these base64 value:
On the Apex class side, I have this code:
String busiLogo = '';
public static void apexMethod(){
busiLogo = ApexPages.currentPage().getParameters().get('vBusiLogo');
String logoName = 'image.png';
String bucketname ='amazon-file-s3';
String host = 's3-ap-sample-1.amazonaws.com';
Blob beforeblob = Blob.valueOf(busiLogo);
String attachmentBody = EncodingUtil.base64Encode(beforeblob);
HttpRequest req = new HttpRequest();
req.setMethod('PUT');
req.setEndpoint('callout:AmazonS3' '/' logoName);
req.setHeader('Host', bucketname '.' host);
req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
req.setHeader('Content-Encoding', 'UTF-8');
req.setHeader('Content-Type','image/png');
req.setHeader('Connection', 'keep-alive');
req.setHeader('Date', formattedDateString);
req.setHeader('ACL', 'public-read-write');
Blob blobFile = EncodingUtil.base64Decode(attachmentBody);
req.setBodyAsBlob(blobFile);
Http http = new Http();
HTTPResponse res = http.send(req);
}
Can you help me how will I send my actual image to s3 file, or where did I go wrong with my code?
CodePudding user response:
I figured out that since the busiLogo variable is base64
encoded, I can just decode it and remove the "data:image/png;base64"
, from it. and then encode the value and send the encoded blob value to S3.