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:
While trying above code you may get below error:
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.
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