Good answers by Willem & AAU. Other than those I was able to find one more way. ContentVersion
& ContentDelivery
. Upload your document as a ContentVersion
& create a related ContentDelivery
record, the latter one contains the public URL for your document. Here is a sample code. I converted Attachment
to a ContentVersion
.
Attachment attach = new Attachment();
attach.Body = filebody;
attach.Name = filename;
attach.ContentType = contentType;
attach.ParentId = account.Id;
insert attach;
ContentVersion cv = new ContentVersion();
cv.VersionData = attach.Body;
cv.Title = attach.Name;
cv.PathOnClient = attach.Name;
insert cv;
ContentDistribution cd = new ContentDistribution();
cd.name = attach.Name;
cd.ContentVersionId = cv.Id;
cd.PreferencesAllowOriginalDownload = true;
cd.PreferencesAllowPDFDownload = true;
cd.PreferencesAllowViewInBrowser = true;
insert cd;
ContentDistribution cdFetched = [SELECT Id, DistributionPublicUrl from ContentDistribution where Id =:cd.Id];
System.debug('Public URL'+cdFetched.DistributionPublicUrl);
The best thing about ContentDelivery
is that it has a Boolean field called PreferencesAllowViewInBrowser
which if true allows you to display the content of the file in browser without any third party document viewer. Pretty Awesome!