How to convert attachment to file in Apex Salesforce

by Rijwan Mohmmed
0 comment
How-to-convert-attachment-to-file-in-Apex-Salesforce

Hello friends today we will learn how to convert attachment to files. We all know we can’t upload a file more then 5 MB but in Files you can upload in GBs. So now mostly users navigate to files instead attachment. If you have files in attachments you can convert these to files easily by Apex class. I will create a Batch Apex Class so you multiple attachments convert in files.

Note:
If you want to modify System audit Fields like CreatedDate, CreatedById fields while converting to file. you should have the below permission “Set Audit Fields upon Record Creation” and “Update Records with Inactive Owners”.

for this Setup-> enter User Interface -> select the checkbox Set Audit Fields upon Record Creation” and “Update Records with Inactive Owners”

ConvertAttachmenttoFile_Batch.cls :

global class ConvertAttachmenttoFile_Batch implements Database.Batchable<sObject> {
    String query = 'SELECT Id, Name, Body, ContentType, ParentId, Description, OwnerId, CreatedDate From Attachment';
	
	global Database.QueryLocator start(Database.BatchableContext bc) {
        // collect the batches of records to be passed to execute
		return Database.getQueryLocator(query);
    }
	
    global void execute(Database.BatchableContext bc, List<Attachment> lstAttachments){
        // process each batch of records
		List<ContentVersion> cvList = new List<ContentVersion>();
		for(Attachment attach : lstAttachments) {
			 ContentVersion cv = new ContentVersion();
			 cv.Title = attach.Name;
			 cv.PathOnClient = '/' + attach.Name;
			 cv.VersionData = (attach.Body == null ? Blob.valueOf('.') : attach.Body);
			 cv.Description = attach.Description;
			 cv.SharingPrivacy = 'N'; // Can be always public.
			 cv.FirstPublishLocationId = attach.ParentId; // Parent Id
			 cv.OwnerId = attach.OwnerId;
             cv.FirstPublishLocationId = attach.OwnerId;
             // if you want to change according attachment then please read about note
			 cv.CreatedById = attach.OwnerId; 
			 cv.CreatedDate = attach.CreatedDate;
			 cvList.add(cv);
		}
		//insert content version
		if(!cvList.isEmpty()) {
			insert cvList;
		}
		//delete attachments if you want
		if(!lstAttachments.isEmpty()) {
			delete lstAttachments;
		}
    }  
	
    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }    
}

Call above Batch class ..

Database.executeBatch(new ConvertAttachmenttoFile_Batch());

You may also like

Leave a Comment