I'm passing the dataURL from JS in the vfp to the extensions class. I'm trying to store that image as an attachment to the custom object. The attachment is uploaded but when I try to open, a "file" (type of file: file) is downloaded which is unable to open. When I paste the dataURL in a browser, I'm able to view the image. So I think I'm making a mistake in the Blob.

imagedataURL --> data:image/png;base64,iVBORw...

public void uploadfile() {

    string imagedataurl = ApexPages.currentPage().GetParameters().Get('imagedataurl');
    System.debug(' DataURL : ' + imagedataurl);
    Blob imageblob = Blob.valueOf(imagedataurl);

    attachment a = new attachment();
    a.ParentId = 'a0Oe000000XXXXXXXA';
    a.Name = 'attachment';
    a.Body = imageblob;
    insert a;

Thanks in advance.

1 Answer 1


You need to specify the file extension when giving name to the attachment.

a.Name = 'attachment.png';

Or alternatively set the ContentType attribute - Attachment Object

Update: Your string is already base64 encoded, so you'll need to strip off the first part (the metadata of the file) and base64 decode the rest (the content):

a.Body = Encodingutil.base64Decode(imagedataURL.substring(imagedataURL.indexOf(',') + 1));

  • I've tried specifying extension in both the ways. a.Name = 'attachment.png'; and a.ContentType = 'Image/png'; Now when I click the view link, it is opening a new tab with broken image icon.
    – Seesh
    Jan 30, 2015 at 0:29
  • I've updated my answer. Your string is already base64 encoded, you have to decode it before you can specify it as a body to the attachment. Jan 30, 2015 at 3:44
  • Perfect. It's working.
    – Seesh
    Jan 30, 2015 at 7:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .