function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ChaturChatur 

Chatter REST API - File Upload using Request body

Hi Everyone,

 

I am trying to upload a file in Chatter by REST API using request body - Since we are not able to send @Mention text with request parameter, we are using request body instead of request parameter to send the file Attachment with feed text having @Mentions together.

 

Please reply it, if anybody has worked on similar problem earlier or has any clue for resolution.

ChrisOctagonChrisOctagon

Hi Chatur,

 

To upload a file for a new feed item in the Chatter REST API, you have to make a multipart request, using the content type "multipart/form-data". This sort of request requires you to define a "boundary" to go between parts, there are examples online. Be careful to get the correct newlines after boundaries and to include a boundary at the end. Each "part" in a multipart request can have its own content-type, so supply your rich body with @ mentions as JSON or XML in an "application/json" or "application/xml" part. The binary file data should be provided in an "image/jpeg" or "application/octet-stream" part named "feedItemFileUpload".

 

There is some example code here: https://github.com/cseymourSF/Chatter-API-iOS-Sample/blob/master/Classes/UserPhotoPoster.m which shows how to upload a file in a multipart request (this isn't a feed item post, so it doesn't inlcude a json/xml part, this code is just used for setting someone's user profile photo, but it should be somewhat helpful).

 

Let us know how it goes.

 

Cheers,

- Chris

remyaMohananremyaMohanan

Hi,

 

I am trying to implement upload functionality but I am getting a 500 internal server error.

 

I am submitting a form first from client side:

<form action='"+ url +"' id='upload_form' enctype='multipart/form-data' method='POST'><li>File to upload: <input type='file' name='upfile'><br><input id='upload_with_atttachment' type='submit' name='uploadedFile' value='Upload'><input type='hidden' name='status' value='"+ status_post +"'><input type='hidden' name='accesstoken' value='"+ token +"'><input type='hidden' name='instanceurl' value='"+ instanceurl +"'>&nbsp;&nbsp;<a id='cancel_upload'>close</a></li></form>

 

and hitting the rest api which does the following:

 

 

@RequestMapping(value="/updateStatus/",method=RequestMethod.POST)
    @ResponseBody
 
    public String updateStatus(@RequestHeader("accesstoken") String token,@RequestHeader("instanceurl") String instance,@RequestParam("status") String status,@RequestParam("upfile") File Ufile )
    throws IOException, AppException
    {  
   
        
       
         String fileName = "fileUp";
        String respBody = "";
        String url="/services/data/v24.0/chatter/feeds/news/me/feed-items";
                
      
        
        Part[] parts = {
               
                new StringPart("fileName", fileName),
                new StringPart("text", status),
                new FilePart("feedItemFileUpload", Ufile),
                
            };
        
        PostMethod pm = new PostMethod(instance + url);  
        
      
         pm.setRequestEntity(new MultipartRequestEntity(parts, pm.getParams()));
         pm.setRequestHeader("Authorization", "OAuth "+token);
         pm.setRequestHeader("Content-Type", "multipart/form-data");
         

         try {
             logger.info("updateStatus execute");
                httpclient.executeMethod(pm);
                respBody = pm.getResponseBodyAsString();
                logger.info("Salesforce: updateStatus(): Response body: " + respBody);
          } catch (HttpException e1){
                logger.info("Error occurred in Salesforce updateStatus():HttpException ", e1.getMessage());
                throw new AppException(e1.getMessage());
          } catch (IOException e2) {
                logger.info("Error occurred in Salesforce updateStatus():IOException ", e2.getMessage());
                throw new AppException(e2.getMessage());
          } finally {
                  pm.releaseConnection();
          }

        return respBody;
    
        
    }

 

 

Can you please tell me where I am wrong!

 

Thanks!!!!

 

ChrisOctagonChrisOctagon

Sorry I can't tell from your code, I dont' know anything about the libraries you're using. A trace of the exact HTTP request being sent would help.

remyaMohananremyaMohanan
Response Headers
Access-Control-Allow-Meth...POST, GET, OPTIONS
Access-Control-Allow-Orig...*
Cache-Controlmax-age=86400
Connectionclose
Content-Encodinggzip
Content-Length392
Content-Typetext/html;charset=utf-8
DateTue, 08 May 2012 19:14:05 GMT
ExpiresWed, 09 May 2012 19:14:05 GMT
ServerApache/2.2.21 (CentOS)
VaryAccept-Encoding
Request Headers
Acceptapplication/json, text/javascript, */*; q=0.01
Accept-Encodinggzip, deflate
Accept-Languageen-us,en;q=0.5
Connectionkeep-alive
Content-Length13
Content-Typeapplication/x-www-form-urlencoded; charset=UTF-8
Cookie**********
Host******
Referer***
User-AgentMozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0
X-Requested-WithXMLHttpRequest
accesstoken***uE************************HusC****xHc********
instanceurl*****
remyaMohananremyaMohanan

I would like to know how to send the information from client side. Do I strictly need to do a form post with enctype="multipart/form-data"?

Also in the chatter pdf there is a sample java code. there is a function called getFile(), what is that function exactly doing.

 

what should be the type of feedItemFileUpload parameter. is that file path location or the binary file itself?

 

The java code which I have used is the same as the snippet which was given in the documentation. so am I doing something wrong in the way I am sending data?

 

Thanks!

ChrisOctagonChrisOctagon

I don't understand the header you posted. It shows a content-type of "application/x-www-form-urlencoded;" but the code you posted is using multipart. You have to use multipart to post a file binary.

ChrisOctagonChrisOctagon

Any HTTP request that includes binary data must be sent with content type "multipart/form-data". I don't know what an "enctype" is.

 

feedItemFileUpload is the name of the binary part that must be included in your multipart request

 

Which documentation did you find a snippet in? 

 

Again, I don't really know the details of the client programming environment you are using. If you post the exact raw HTTP request from a sniffer like WireShark then I might be able to help.

remyaMohananremyaMohanan

I got the java snippet from the following document:

 

http://www.salesforce.com/us/developer/docs/chatterapi/salesforce_chatter_rest_api.pdf

page no:101 : example in Java of updating a news feed with a file post

 

 

 

 

 

 

ChrisOctagonChrisOctagon

Sorry, it looks like that sample code is wrong at least in the content-type value. The content type must be multipart. If you provide me with the raw HTTP request you're sending from Wireshark or Fiddler then I cant give you more assistance, I don't know anything about how Java creates HTTP requests.

remyaMohananremyaMohanan
Request Headersview source
Accepttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encodinggzip, deflate
Accept-Languageen-us,en;q=0.5
Connectionkeep-alive
Cookie*****
Host*****
Referer*****
User-AgentMozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0
Request Headers From Upload Stream
Content-Length1524
Content-Type

multipart/form-data; boundary=---------------------------283232113224472

 

 

ChrisOctagonChrisOctagon

The request header you've posted looks fine. I need to see the full request to help figure out what's wrong. There are sub-headers inside for each of the 3 parts you're sending.