Saturday, February 25, 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:



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.




More Blogs>>: BOX AND SALESFORCE INTEGRATION    
INTEGRATING BOX FILE PICKER WITH SALESFORCE
REST API TUTORIAL FOR SALESFORCE




1 comment:

  1. Hi There,

    Seems like I won the lottery here….This is a treasure box of blogs and your folks are like leprechauns! Phenomenal read on Fetching file from external/public URL and storing it into Salesforce !

    when user select an account from the picklist, all opportunities which are related to that account should be displayed in a table with checkbox in a first column of each row, there should be one master checkbox in the header of the table to select or deselect all opportunities in one click.

    By the way do you have any YouTube videos, would love to watch it. I would like to connect you on LinkedIn, great to have experts like you in my connection (In case, if you don’t have any issues).

    Kind Regards,
    Preethi.

    ReplyDelete