How do I upload file using Salesforce Mobile SDK f

2019-09-04 00:19发布

I am using the Salesforce SDK (4.1.x) in a native Android app. I use the RestClient.sendAsync method to post my form data to a custom object. That part is working fine. Now I need to upload and attach a photo that was taken by the mobile user. I see that RestClient has an uploadFile method. Is this the correct method? If so then how do I connect the uploaded file to the custom form data?

1条回答
你好瞎i
2楼-- · 2019-09-04 01:05

Ok. I figured this out. First, create the parent object (the main form data) using the following.

request = RestRequest.getRequestForCreate(apiVersion, objectType, fields);
client.sendAsync(restRequest, new RestClient.AsyncRequestCallback() {...

In the onSuccess method you will get the id of the new object from the response. There are plenty of examples that show how to get the JSON object and the id. Armed with this parentId we can now create the attachment. The code looks something like this.

private void postImageAsAttachment(String parentId, String title) {
    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put("Name", title);
    fields.put("ParentId", parentId);
    fields.put("Body", ImageHelper.getBase64FromImage(mCurrentPhotoPath));

    RestRequest request = null;
    try {
        request = RestRequest.getRequestForCreate(apiVersion, "Attachment", fields);
    } catch (Exception ex) {
        Log.d(TAG, "sendRequest: ", ex);
        Toast.makeText(MainActivity.this, "The file upload failed: " + ex.toString(), Toast.LENGTH_LONG).show();
    }
    client.sendAsync(request, new RestClient.AsyncRequestCallback() {...

I'm using a simple class called ImageHelper that simply loads the image file, performs image compression (if necessary), and base64 encodes the image data. The result is that an "Attachment" object is created as a child of the parent object.

I hope this helps the next person.

查看更多
登录 后发表回答