0

I've created my own custom Solution object for SF Lightning use. I'm trying to migrate existing SF Classic Solution's Attachment Body blob data to ContentVersion versionData blob data. Below is the code i used to copy over Attachment to ContentVersion.

Map<String, Solution> solutions = new Map<String, Solution>();
Map<String, List<Attachment>> attachments = new Map<String, List<Attachment>>();
Set<Id> attachmentIds = new Set<Id>();

for (Solution s: [select SolutionName, (select Id, Name from Attachments) from Solution]){
    if (!s.Attachments.isEmpty()){
        Solution sol = new Solution();
        sol.SolutionName = s.SolutionName;
        attachments.put(s.SolutionName, s.Attachments);
        solutions.put(s.SolutionName, s);

        for (Attachment a : s.Attachments){
            attachmentIds.add(a.Id);
        }
    }
}

Solution__c[] sols = [select Id, Solution_Title__c from Solution__c where Solution_Title__c in :solutions.keySet()];

Map<Id, Attachment> attachmentMap = new Map<Id, Attachment>([select Body from Attachment where Id in :attachmentIds]);

ContentVersion[] contentVersions = new ContentVersion[0];

for (Solution__c s: sols){

    for (Attachment a : attachments.get(s.Solution_Title__c)){
        ContentVersion cv = new ContentVersion();
        Blob bval = attachmentMap.get(a.Id).Body;

        cv.Title = a.Name.substringBeforeLast('.');
        cv.PathOnClient = a.Name;
        cv.VersionData = bval;
        cv.FirstPublishLocationId = s.Id;
        cv.ContentLocation = 'S';
        cv.Origin = 'C';
        contentVersions.add(cv);
    }
}

insert contentVersions;

In my custom Solution record page, I have a widget that accepts File upload Attachment and display all available attachments in data table rows. Since I've copy Attachment data to ContentVersion, file attachments will be present in the widget as shown in the image below (apologies on the redacted images). If i click the hyperlink of the file attachment, it will open the file's sobject record page.

Custom solution record page with file attachments from ContentVersion

However the file that was copied over from Attachment is unable to preview. Though download works fine.

ContentVersion versionData file that is copied from Attachment's Body cannot be previewed

If i manually upload the same file that I've downloaded and click on the file's hyperlink, the record page is able to show the preview of the file.

However manual upload of the same file can be previewed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.