[SalesForce] How to save Base64 image data as salesforce attachment

We are integrating an IOS app with salesforce and need to upload image data by apex rest class. we packed image base64 data and other data into JSON string, then send it.
Now we get the JSON data in apex class but have no idea how to save the base64 image data as salesforce attachment.

This is Json data sample:

{
  "records" : [
    {
      "records" : "Image Base64 Data"
    },
    {
      "records" : "Image Base64 Data"
    }
  ]
}

This is apex rest class,

@RestResource(urlMapping='/MyWebService/*')
global class MyWebService 
{
    @HttpPost
    global static void receiveData(String a)
    {  
        String jsonStr = EncodingUtil.base64Decode(a).toString();
        JSONParser parser = JSON.createParser(jsonStr);
        while (parser.nextToken() != null) {
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME){
                String fieldName = parser.getText();
            }
            if (parser.getCurrentToken() == JSONToken.VALUE_STRING){
                Attachment attach = new Attachment();
                **attach.Body = parser.getBlobValue();**
                attach.Name='Test';
                attach.ContentType='image/jpg';
                attach.ParentId='0019000000v8W34';
                insert attach;
            }
        }
    }
}

As a result, we can't save image base64 data as attachment body. We checked logs, got StringException error and totally have no idea what happened.
Did anyone got this and how to solve it? Thanks in advance.

Best Answer

You can do it like this:

jsonStr = EncodingUtil.base64Decode(jsonData).toString();
List<Attachment> attaches = new List<Attachment>();
for(Records record : parse(jsonStr).records)
{
     attaches.addAll(buildAttachment(record));
}
insert attaches;

global static List<Attachment> buildAttachment(Records data)
{
    List<Attachment> attaches = new List<Attachment>();
    if(data.name == 'SFA_Photo')
    {
        for(String str : data.values)
        {
            String[] dataList = str.split('\\|');
            if(dataList[1].startsWith('001'))
            {
                Attachment attach = new Attachment();
                attach.contentType = 'image/jpg';
                attach.name = dataList[0];
                attach.parentId = dataList[1];
                attach.body = EncodingUtil.base64Decode(dataList[2]);
                attaches.add(attach);   
            }
        }
    }
    return attaches;
}
Related Topic