+ Start a Discussion
Tad Aalgaard 3Tad Aalgaard 3 

Trying to upload a file via RestAPI into Chatter, getting error "Binary data included but file attachment information is missing"

I am getting an error when trying a file into Chatter via RestAPI.

[{"errorCode":"POST_BODY_PARSE_ERROR","message":"Binary data included but file attachment information is missing. If providing rich JSON/XML input in multipart REST, make sure to include Content-Type header in the part."}]

Here is a snippet of my code, what am I missing?
 
DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost;
        MultipartEntity reqEntity;
        httppost = new HttpPost(RES_URL);
        reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        File imageFile = new File(
                "/salesforce/wsdl/test.txt");
        FileBody bin = new FileBody(imageFile);
        reqEntity.addPart("feedItemFileUpload", bin);
        String fileName = "test.txt";
        // file name can be text plain only, though using text/html doesn't breaks
        reqEntity.addPart("fileName", new StringBody(fileName, "text/plain",
                Charset.defaultCharset()));

        httppost.setEntity(reqEntity);

        httppost.setHeader("Authorization",         "OAuth " + logon());

        String response = EntityUtils.toString(httpclient.execute(httppost)
                .getEntity(), "UTF-8");

        System.out.println(response);

 
SonamSonam (Salesforce Developers) 
Hey Tad, could you please check the code snippet provided in the link below:
https://developer.salesforce.com/forums/ForumsMain?id=906F00000009APDIA2
http://salesforce.stackexchange.com/questions/36493/uploading-a-file-to-chatter-rest-api
 
Tad Aalgaard 3Tad Aalgaard 3
In the other post you referenced, what would my json String look like?  Can you provide an example?
Tad Aalgaard 3Tad Aalgaard 3
I switched gears a bit and now am working with the following code.  But getting an error. 
 
status : 400
Response Content Length : -1
response : [{"message":"multipart form upload failed because field 'Json' exceeds max length 10485760","errorCode":"INVALID_MULTIPART_REQUEST"}]
 getStatusCode 400 getStatusText : Bad Request
Error handling logic


 
package wsc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream; 
import java.io.UnsupportedEncodingException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.PartBase;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONException;
import org.json.JSONObject;


public class aa {

    private class JsonPart extends PartBase {

        private byte[] bytes;

        public JsonPart(String name, String json) throws IOException {
            super(name, "application/json", "UTF-8", null);
            this.bytes = json.getBytes("UTF-8");
        }

        @Override
        protected void sendData(OutputStream os) throws IOException {
            os.write(bytes);
        }

        @Override
        protected long lengthOfData() throws IOException {
            return bytes.length;
        }
    }

    /**
     * Create attachment SObject from its JSON populating its Body from a file at the same time.
     */
    public void createAttachment(String attachmentJson, File attachmentFile) throws Exception {

        PostMethod post = new PostMethod( "https://XYZ.my.salesforce.com/services/data/v30.0/sobjects/ContentVersion" );// test na14 cs7        
        
        post.setRequestHeader("Authorization", "OAuth " +  logon() );

        try {

            Part[] parts = new Part[] {
                    new JsonPart("Json", attachmentJson),
            };

            MultipartRequestEntity mpe = new MultipartRequestEntity(parts, post.getParams());            
            post.setRequestEntity(mpe);

            HttpClient httpClient = new HttpClient();

            int status = httpClient.executeMethod(post); 
            String response = post.getResponseBodyAsString();

            System.out.println(" status : " + status);          
            System.out.println("Response Content Length : " + post.getResponseContentLength());         
            System.out.println("response : " + response);            
            System.out.println(" getStatusCode " + post.getStatusCode() + " getStatusText : " + post.getStatusText());

            if (post.getStatusCode() == HttpStatus.SC_CREATED) {
                System.out.println("Logic for OK");
            } else {
                System.out.println("Error handling logic");
            }
        } catch (Exception e) {
            e.printStackTrace();
        
        } finally {
            post.releaseConnection();
        }
    }

    public static void main(String[] args) {

        JSONObject obj = new JSONObject();
        try {           
            File f = new File("/salesforce/wsdl/test.zip");
            obj.put("Description", "Last Modified : " + f.lastModified() );
            String path = "C:\\salesforce\\wsdl\\test.zip";
            
        	// Read the file
            byte[] data = loadFileAsByteArray(path);
    
            obj.put("VersionData", new String(Base64.encodeBase64(data)));
            obj.put("PathOnClient", path);
            obj.put("Title", "blah");
            obj.put("Description", "blah");
            
            String name = f.getName();           

            aa ob = new aa();
            ob.createAttachment(obj.toString(), f);

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    
	static String logon() {
 // removed sensitive data
	
			return blah;
	
	}    
    // Simplest read of an entire file into a byte array
    // Will throw exceptions for file not found etc
    private static byte[] loadFileAsByteArray(String path) throws IOException {
        File file = new File(path);

        InputStream is = new FileInputStream(file);

        byte[] data = new byte[(int) file.length()];

        is.read(data);

        return data;
    }	

}

 
neelam mooreneelam moore
Hi Tad, Were you able to find the root cause of this error "multipart form upload failed because field 'Json' exceeds max length 10485760" . I m trying to do a similar REST api call but i m encountering this problem.