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
klppkklppk 

How to read Salesforce Attachment using partner WSDL java API and store it as a File.

Code Details:

QueryResult queryResults = partnerConnection.query("SELECT Body FROM Attachment WHERE Id = '"+attachment_id+"'");    
SObject[] sObjList = queryResults.getRecords();
SObject attachment = sObjList[0];

Now I need to store the attachment (JPG file) as a file in my Server. Please provide your suggestions to achieve it. Thanks. 
            
Best Answer chosen by klppk
klppkklppk
QueryResult queryResults = partnerConnection.query("SELECT Name, Body FROM Attachment WHERE Id = '"+attachment_id+"'");    
SObject[] sObjList = queryResults.getRecords();
SObject attachment = sObjList[0];

String attStr = (String)attachment.getField("Body");
f1=new File("C:/"+attachment.getField("Name"));
FileOutputStream output = new FileOutputStream(f1);
output.write(Base64.decode(attStr.getBytes()));
The above code worked finally! Thanks.
 

All Answers

Sumeet_ForceSumeet_Force
Here you go :
if (queryResultsAttach.getSize() > 0) {
for (int i=0;i<queryResultsAttach.getRecords().length;i++) {
    q = (Attachment)queryResultsAttach.getRecords()[i];
    int size = q.getBody().length;
    f1=new File("C:/"+q.getName());
    byte[] buffer= new byte[size];
    buffer = q.getBody();
    FileOutputStream output = new FileOutputStream(f1);
    output.write(buffer);
}
}
klppkklppk
@Sumeet - I am getting type cast error to convert SObject to Attachment. And the getBody() method is not available in the Attachment class.
Screenshot
klppkklppk
QueryResult queryResults = partnerConnection.query("SELECT Name, Body FROM Attachment WHERE Id = '"+attachment_id+"'");    
SObject[] sObjList = queryResults.getRecords();
SObject attachment = sObjList[0];

String attStr = (String)attachment.getField("Body");
f1=new File("C:/"+attachment.getField("Name"));
FileOutputStream output = new FileOutputStream(f1);
output.write(Base64.decode(attStr.getBytes()));
The above code worked finally! Thanks.
 
This was selected as the best answer
Sumeet_ForceSumeet_Force
great ! you can mark this question as solved then by choosing one of above answers !