Thursday, July 6, 2017

Fetching file from external/public URL and storing it into Salesforce

If you have file URL for file stored outside the salesforce, then you can fetch file information from external URL by performing a call out to external system and store the file in salesforce.

For Demo purpose, I have uploaded a pdf file in Google drive and shared it with link with people. Now I will fetch this file and will store it as attachment in salesforce under account record.

File URL-  https://drive.google.com/file/d/0ByXILxflqQ2jWGpNVmI1WW9uYTQ/view?usp=sharing


Below is apex class which will help us to perform this activity:
Public class FileDownLoadUtility{
public static blob fetchFileFromExternalUrl(String extFileUrl){
//extFileUrl='https://drive.google.com/file/d/0ByXILxflqQ2jWGpNVmI1WW9uYTQ/view?usp=sharing';
Http h = new Http();
HttpRequest req = new HttpRequest();
//Replace any spaces in extFileUrl with %20
extFileUrl = extFileUrl.replace(' ', '%20');
//Set the end point URL
req.setEndpoint(extFileUrl);
req.setMethod('GET');
req.setHeader('Content-Type', 'application/pdf');
req.setCompressed(true);
req.setTimeout(60000);
//Now Send HTTP Request
HttpResponse res = h.send(req);
system.debug('Response from Server: ' + res.getBody());
//getBodyAsBlob method was will convert the response into Blob
blob retFile = res.getBodyAsBlob();
return retFile;
}
public static Id createAttachment(blob fileContent, String recordId, String fileType){
//for pdf files content type should be pdf
//for jpeg file content type should be image/jpeg
Attachment attach = new Attachment();
attach.ParentId = recordId;
attach.Name = 'FileFromExtenalSource.pdf';
attach.Body = fileContent;
attach.contentType = fileType;
insert attach;
return attach.id;
}
}


Now you can run below code in developer console to test this:

//you can specify any record Id where you want to store file as attachment
String RecordId='0019000000ld4kN'; 
String fileContentType='pdf';
String extFileURL='https://drive.google.com/file/d/0ByXILxflqQ2jWGpNVmI1WW9uYTQ/view?usp=sharing';
blob fileBlob=FileDownLoadUtility.fetchFileFromExternalUrl(extFileURL);
Id attachmentId = FileDownLoadUtility.createAttachment(fileBlob, RecordId , fileContentType);
system.debug('*****attachmentId:'+attachmentId);

Note: 
  • If you are trying to fetch file from external source which is authenticated, then pass authorization parameters in HTTP Request headers
  • You should specify the file content type before creating attachment in order to properly view file.
  • You can add additional parameter as fileName in "createAttachment" method, if you you want specify the attachment name while creating attachment.

While trying above code you may get below error: 

For this you need to add external URL in Remote Site Settings. For this example, I have added "https://drive.google.com/" in remote site settings.

No comments:

Post a Comment