1

I am attempting to convert an apex attachment into a blob. My visualforce code is

    <div class="mt-5 row">
        <div class="d-flex justify-content-center col-lg-12">
            <h1>Upload an Attachment To S3</h1>
        </div>
    </div>
    <div class="row">
        <div class="d-flex justify-content-center col-lg-12">
            <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
        </div>
    </div>
    <div class="mt-1 row">
        <div class="d-flex justify-content-center col-lg-12">
            <apex:commandbutton value="Save" action="{!convertDocToBlob}" id="saveButtonForS3" />
        </div>
    </div>

My apex is

public Pagereference convertDocForS3(){
    String sObjID = System.currentPagereference().getParameters().get('id');

    Attachment a = new Attachment(parentId = sObjID, name=myfile.name, body = myfile.body);

    Blob testBlob = convertToBlob(a);

    return null;
}

public Blob convertToBlob(Attachment attach){
    Blob testBlob = EncodingUtil.base64Decode(attach.body.ToString());
    return testBlob;
}

When I attempt to upload at png file, the error I get back is

 System.StringException: BLOB is not a valid UTF-8 string

EDIT: The correct thing to do in this case was

 Blob testBlob = a.body;

as the attachment was already coming through as a blob.

5
  • What's you goal here? What's the type of value in attach.body (using system.debug)? Oct 31 '19 at 19:24
  • I need to upload a file to AWS S3 by sending a Blob. My debug says a.body is 13:29:26.0 (26058257)|USER_DEBUG|[25]|DEBUG|Blob[8999]
    – ccarlson
    Oct 31 '19 at 19:30
  • 1
    It looks like attach.body is already a blob so not sure you need to use .ToString() and then base64Decode to recreate it. Is there a different part of the code that actually sends it to AWS or do you have a certain format requirement? If you simply pass the attach.body does it work? Oct 31 '19 at 19:34
  • I actually didn't try, I'll give it a shot now. I assumed it wasn't a blob, to be honest.
    – ccarlson
    Oct 31 '19 at 19:38
  • 1
    @KrisGoncalves - you should post the answer as your comment is correct
    – cropredy
    Oct 31 '19 at 21:28
1

Since you're pulling the info from an uploaded file, the body of the attachment is already a blob. If the requirement is just to pass the blob to another location then there's no need to manipulate it.

The error was you using base64Decode which expects a Base64-encoded String which .toString does not return

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_encodingUtil.htm

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.