+ Start a Discussion
Sandeep AgrawalSandeep Agrawal 

Attaching image to chatter post

I want to add image to the content which  I am  posting to chatter.

I am using chatter rest api but not able to do it..

 

Any kind of help will be greatful.

 

I am using below code for uploading image to chatter post using restapi.

if (imageFile != null && fileName != null && imageTitle != null)
				{
					String url = salesforceRestClient.getClientInfo().instanceUrl + "/services/data/" + SF_API_VERSION + "/chatter/feeds/news/me/feed-items";
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost ;
					MultipartEntity reqEntity ;
					httppost = new HttpPost(url);
					reqEntity = new MultipartEntity(
							HttpMultipartMode.BROWSER_COMPATIBLE);
					FileBody bin = new FileBody(imageFile);
					reqEntity.addPart("feedItemFileUpload", bin);
					reqEntity.addPart("fileName", new StringBody(fileName, "text/html", Charset.defaultCharset()));
					reqEntity.addPart("text", new StringBody(noteContent, "text/html", Charset.defaultCharset()));
					reqEntity.addPart("feedItemFileUpload", new FileBody(imageFile, fileName, "application/octet-stream", Charset.defaultCharset().toString()));
					httppost.setEntity(reqEntity);
					httppost.setHeader("Authorization", "OAuth " + salesforceRestClient.getAuthToken());
					publishResponse = salesforceRestClient.sendSync(RestMethod.POST, url,reqEntity);
					NotepriseLogger.logMessage("responseBody"+publishResponse);
//					HttpResponse response = httpclient.execute(httppost);
//					HttpEntity resEntity = response.getEntity();

 Thanks

 

 

I have successfully able to post image to my own chatter wall but when I am posting it to user wall, it is giving me error. I am not able to take http request log some how.

 

Below is the code which I am using:

PostMethod postMethod = null;  

String stringBody = generateJSONBodyForChatterFeed(noteContent, selectedIds, null, fileName, imageTitle);      
String url = salesforceRestClient.getClientInfo().instanceUrl + "/services/data/" + SF_API_VERSION + "/chatter/feeds/news/me/feed-items";

Part[] parts = {
                                        new StringPart("desc", "Description"),
                                        new StringPart("fileName", fileName),
                                        new StringPart("text", noteContent),                                                                                
                                        new FilePart("feedItemFileUpload", imageFile),
                                    };
                        postMethod = new PostMethod(url);
                        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

postMethod.setRequestHeader("Authorization", "OAuth " + salesforceRestClient.getAuthToken());                                
                    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

 


 

Here is generateJSONBodyForChatterFeed method code:

 

public static String generateJSONBodyForChatterFeed(String content, ArrayList<String> mentionIds, String imageDescription, String fileName, String imageTitle)
    {
        JSONArray msg = new JSONArray();
        String bodyString = null;
        JSONObject requestJSON=null;
        try
        {            
            if (mentionIds != null)
            {
                for (int i = 0; i < mentionIds.size(); i++)
                {
                    JSONObject mention = new JSONObject();                
                    mention.put("type", "mention");
                    mention.put("id", mentionIds.get(i));
                    msg.put(mention);
                }                
            }
            if (content != null)
            {
                JSONObject text = new JSONObject();
                text.put("type", "text");
                
                text.put("text", " " + content);
                msg.put(text);
            }    
            JSONObject attachment = null;
            if (fileName != null && imageTitle != null)
            {
                attachment = new JSONObject();
                attachment.putOpt("desc", imageDescription);
                attachment.putOpt("fileName", fileName);
                attachment.putOpt("title", imageTitle);
            }
            requestJSON= new JSONObject();
            requestJSON.putOpt("body", new JSONObject().put("messageSegments", msg));
            if (attachment != null)
            {
                requestJSON.putOpt("attachment", attachment);
            }
            bodyString = requestJSON.toString();
            NotepriseLogger.logMessage("Json"+requestJSON);            
        }  
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    
        return bodyString;
    }

 

 

Please let me know what mistake I am doing here. When I add bosy part , it is just skipping that and posting the image to my own wall instead of user.

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
ChrisOctagonChrisOctagon

just a shot in the dark, but maybe try a variant of this approach? if this doesn't work out i will try and put together a sample Java application for doing this stuff, may take me a few days to get to it though
 
http://evgeny-goldin.com/blog/uploading-files-multipart-post-apache/

HttpPost        post   = new HttpPost( url );
MultipartEntity entity = new MultipartEntity();
 
// File
entity.addPart( "feedItemFileUpload", new FileBody((( File ) paramValue ), "application/octet-stream" ));
 
// JSON
entity.addPart( "json", new StringBody( <json string>, "application/json", Charset.forName( "UTF-8" )));
 
post.setEntity( entity );

All Answers

ChrisOctagonChrisOctagon

Hi Sandeep,

 

What error are you getting? In newer versions of the Chatter REST API I think you should use "title" instead of "fileName". Also it looks like you're adding the part "feedItemFileUpload" twice in your code. Are you able to get additional info about the raw HTTP request that is being sent, such as its content-type value?

 

- Chris

Sandeep AgrawalSandeep Agrawal

I have successfully able to post image to my own chatter wall but when I am posting it to user wall, it is not working. I am not able to take http request log some how.

 

Below is the code which I am using:

PostMethod postMethod = null;  

String stringBody = generateJSONBodyForChatterFeed(noteContent, selectedIds, null, fileName, imageTitle);      
String url = salesforceRestClient.getClientInfo().instanceUrl + "/services/data/" + SF_API_VERSION + "/chatter/feeds/news/me/feed-items";

Part[] parts = {
                                        new StringPart("desc", "Description"),
                                        new StringPart("fileName", fileName),
                                        new StringPart("text", noteContent),                                                                                
                                        new FilePart("feedItemFileUpload", imageFile),
                                    };
                        postMethod = new PostMethod(url);
                        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

postMethod.setRequestHeader("Authorization", "OAuth " + salesforceRestClient.getAuthToken());                                
                    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

 


 

Here is generateJSONBodyForChatterFeed method code:

 

public static String generateJSONBodyForChatterFeed(String content, ArrayList<String> mentionIds, String imageDescription, String fileName, String imageTitle)
    {
        JSONArray msg = new JSONArray();
        String bodyString = null;
        JSONObject requestJSON=null;
        try
        {            
            if (mentionIds != null)
            {
                for (int i = 0; i < mentionIds.size(); i++)
                {
                    JSONObject mention = new JSONObject();                
                    mention.put("type", "mention");
                    mention.put("id", mentionIds.get(i));
                    msg.put(mention);
                }                
            }
            if (content != null)
            {
                JSONObject text = new JSONObject();
                text.put("type", "text");
                
                text.put("text", " " + content);
                msg.put(text);
            }    
            JSONObject attachment = null;
            if (fileName != null && imageTitle != null)
            {
                attachment = new JSONObject();
                attachment.putOpt("desc", imageDescription);
                attachment.putOpt("fileName", fileName);
                attachment.putOpt("title", imageTitle);
            }
            requestJSON= new JSONObject();
            requestJSON.putOpt("body", new JSONObject().put("messageSegments", msg));
            if (attachment != null)
            {
                requestJSON.putOpt("attachment", attachment);
            }
            bodyString = requestJSON.toString();
            NotepriseLogger.logMessage("Json"+requestJSON);            
        }  
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    
        return bodyString;
    }

 

 

Please let me know what mistake I am doing here. When I add bosy part , it is just skipping that and posting the image to my own wall instead of user.

 

Thanks

ChrisOctagonChrisOctagon

The URL you are using is /chatter/feeds/news/me/feed-items. Posting to this posts to your user profile. To post to someone else's wall, use:

 

/chatter/feeds/user-profile/<TARGET USER ID>/feed-items

Sandeep AgrawalSandeep Agrawal

URL is not the issue. I am getting below error

"[{"message":"Creating a text post requires text","errorCode":"MISSING_ARGUMENT"}]"

 

If I remove below line :

postMethod.setRequestHeader("Content-type", "multipart/form-data");

 

it is giving this error

[{"message":"Text posts should not include binary data.","errorCode":"POST_BODY_PARSE_ERROR"}]

 

Please let me know working code if you have.

Thanks

 

ChrisOctagonChrisOctagon

You said: "I have successfully able to post image to my own chatter wall but when I am posting it to user wall, it is not working" The ony difference between these 2 scenarios should be the URL.

 

In your sample code, you make "stringBody", but I do not see how it is included in the multipart request. Are you adding a part for it? You don't seem to be including it as a part. It should be included as a part with content-type of application/json.

 

Clients are not permitted to mix JSON with simple query parameters like text/desc/fileName in the same request. A multipart request to the Chatter REST API must be either made up of a bunch of simple (StringPart) parts along with a binary part, OR a single JSON part along with a binary part. It looks like you want to include mentions in the body, so you should only have a JSON part and a binary part in your request.

 

The "Text posts should not include binary data." error means that you provided binary data but your attachment information didn't get processed. I suspect this is happening because your JSON is missing the "attachment" section. Can you please provide the exact JSON you are including in your request?

Sandeep AgrawalSandeep Agrawal

I am adding string body like this

new StringPart("body", Stringbody),

 

this is the output of the json which is generating

 

{"body":{"messageSegments":[{"id":"00590000000kT5aAAE","type":"mention"},{"id":"00590000000kT5GAAU","type":"mention"},{"type":"text","text":" \n\n\nfwfwfwfwf wfwfwfw\n"}]},"attachment":{"fileName":"sandeep","title":"sandeep"}} 

 

Can you let me know how can I add json by setting  content-type of application/json in my code?

 

My josn is having the attachment section with mention as I am sending it to 2 users.

 

Please let me know what modification I need to make in this.?

Thanks

 

 

Sandeep AgrawalSandeep Agrawal
Part[] parts = { 
new StringPart("desc", "Description"),
new StringPart("fileName", fileName),
new StringPart("text", noteContent), 
new FilePart("feedItemFileUpload", imageFile),
};
postMethod = new PostMethod(url);
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

httpPost.setHeader("Authorization", "OAuth " + salesforceRestClient.getAuthToken());
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
		client.executeMethod(postMethod);

 Use above message to post image to own wall.

 

Can you tell me what changes I need to do in this code to post the image to user wall.

Thanks

ChrisOctagonChrisOctagon

I think it should look like:

 

StringPart jsonPart = new StringPart("json", <json body>);

jsonPart.setContentType("application/json");

 

Part[] parts = {

  jsonPart,

  new FilePart("feedItemFileUpload", imageFile)};

 

do not supply additional string parts for desc/filename/text. Those values should already be in your JSON.

Sandeep AgrawalSandeep Agrawal

I tried this code but getting error: "[{"message":"Creating a text post requires text","errorCode":"MISSING_ARGUMENT"}]"

String stringBody = generateJSONBodyForChatterFeed("sandeep", selectedIds, null, fileName, imageTitle);    
 String url = salesforceRestClient.getClientInfo().instanceUrl + "/services/data/" + SF_API_VERSION + "/chatter/feeds/news/me/feed-items";

PostMethod postMethod = null;    
                postMethod = new PostMethod(url);

StringPart jsonPart = new StringPart("json",stringBody);
                        jsonPart.setContentType("application/json");
                        Part[] parts = {                                 
                                jsonPart,                                                                
                                new FilePart("feedItemFileUpload", imageFile),
                            };
                        postMethod = new PostMethod(url);
                        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

    postMethod.setRequestHeader("Authorization", "OAuth " + salesforceRestClient.getAuthToken());
                postMethod.addRequestHeader("Content-Type","multipart/form-data");


                org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
                int code =client.executeMethod(postMethod);

 Can you please share the working code to me?

 

I tried all possible way to solve this issue but not getting the success.

Thanks

ChrisOctagonChrisOctagon

Sorry, I think I would need the raw HTTP request to help you further. Please use Wireshark to trace your HTTP request.

ChrisOctagonChrisOctagon

just a shot in the dark, but maybe try a variant of this approach? if this doesn't work out i will try and put together a sample Java application for doing this stuff, may take me a few days to get to it though
 
http://evgeny-goldin.com/blog/uploading-files-multipart-post-apache/

HttpPost        post   = new HttpPost( url );
MultipartEntity entity = new MultipartEntity();
 
// File
entity.addPart( "feedItemFileUpload", new FileBody((( File ) paramValue ), "application/octet-stream" ));
 
// JSON
entity.addPart( "json", new StringBody( <json string>, "application/json", Charset.forName( "UTF-8" )));
 
post.setEntity( entity );

This was selected as the best answer
Sandeep AgrawalSandeep Agrawal

I have already tried this method and I am getting this error for this

 

"09-21 10:48:46.098: V/Noteprise(1412): An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact <a href="https://na1.salesforce.com/_ui/training/help/pub/UserEdSolution?id=50130000000M9gH&orgId=00D000000000062">Salesforce Support</a>. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience. <br/><br/>Thank you again for your patience and assistance. And thanks for using salesforce.com!
09-21 10:48:46.098: V/Noteprise(1412): <br><br>
09-21 10:48:46.098: V/Noteprise(1412): Error ID: 455177138-6359 (1260892324)
"

I am using eclipse and I can't take logs on it as when I am setting the proxt to take the logs it is giving me authentication error.

Thanks

Sandeep AgrawalSandeep Agrawal

Finally I solved the issye and Below is the working code :

String stringBody = generateJSONBodyForChatterFeed(noteContent, selectedIds, null, fileName, imageTitle);				
				String url = salesforceRestClient.getClientInfo().instanceUrl + "/services/data/" + SF_API_VERSION + "/chatter/feeds/news/me/feed-items";
	
				if (imageFile != null && fileName != null && imageTitle != null)
				{
						PostMethod postMethod = null;	
						postMethod = new PostMethod(url);	
						StringPart jsonPart = new StringPart("json",stringBody);
						jsonPart.setContentType("application/json");
						FilePart filePart= new FilePart("feedItemFileUpload", imageFile);
						filePart.setContentType("image/png");
						
						Part[] parts = { 								
								jsonPart,																
								filePart,
								new StringPart("text", "noteContent"),
							};
						postMethod = new PostMethod(url);
						postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
						NotepriseLogger.logMessage("sandeep");
						
					
				
				
				postMethod.setRequestHeader("Authorization", "OAuth " + salesforceRestClient.getAuthToken());
		
				
				org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
				publishResponse =client.executeMethod(postMethod);

 Thanks for your support.

 

ChrisOctagonChrisOctagon

Great, glad to hear you got it working. I don't think that "text" StringPart is going to be used there though.

Sandeep AgrawalSandeep Agrawal

yes it won't require here.