Attaching a Document to a Record in Salesforce.com (Java)
October 10th, 2008
The follow code allows you to upload a physical file to Salesforce.com and attach it to a record.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /**
* See the following:
* API Docs: http://www.salesforce.com/us/developer/docs/sforce70/wwhelp/wwhimpl/js/html/wwhelp.htmhref=sforce_API_objects_Attachment.html
* Example: http://community.salesforce.com/sforce/board/messageboard.id=JAVA_development&message.id=4223
*/
try {
File f = new File("c:\java\test.docx");
InputStream is = new FileInputStream(f);
byte[] inbuff = new byte[(int)f.length()];
is.read(inbuff);
Attachment attach = new Attachment();
attach.setBody(inbuff);
attach.setName("test.docx");
attach.setIsPrivate(false);
// attach to an object in SFDC
attach.setParentId("a0f600000008Q4f");
SaveResult sr = binding.create(new com.sforce.soap.enterprise.sobject.SObject[] {attach})[0];
if (sr.isSuccess()) {
System.out.println("Successfully added attachment.");
} else {
System.out.println("Error adding attachment: " + sr.getErrors(0).getMessage());
}
} catch (FileNotFoundException fnf) {
System.out.println("File Not Found: " +fnf.getMessage());
} catch (IOException io) {
System.out.println("IO: " +io.getMessage());
} |
Categories: Code Sample, Java, Salesforce













Hi Jeff,
I have an issue where user wants to attach a video file to his case object . As we know SFDC doesn’t allow for large size files . and my second question is if I want store this attachments in Amazon , then will it be the best way for avoiding to store attachments in SFDC. (note: only few user must be able to upload and access the attachments and for both action they use only SFDc as interface )
Have you looked at the FTP Attachments app on the AppExchange? I’ve used it and it works quite well. You can upload files to a separate server with essentially the same UI experience inside Salesforce.com.
Hi jeff,
do you have sample code for downloading attachment?
Gary, we have just integrated Click and Pledge to our website and will be using SalesForce as our CRM instead of a collection of old word mailmerge docs and Excel spreadsheets now. We are a non-profit and my responsibility is fundraising among others. SFc has a Donor Management module that seems way cool, but one of the things we do is sell sponsorships for advertising space at Golf Tournaments, Benefit Banquets, etc. I capture the company info, but I need to have them upload hi-res PDF files for their ad. Is there a native way to do this, or should I just have them send an email attachment.? I have worked with large server-based CRM and PC based, will figure Salesforce out quick I expect.