How to convert attachment to file in Apex Salesforce

by Rijwan Mohmmed
2 comments
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());

Test Class:

@isTest
private class ConvertAttachmenttoFile_BatchTest {

      static testMethod void testAttachments() {
        Account acc=new Account(Name='Acme Inc');
        insert acc;
        
        Attachment attach=new Attachment();   	
    	attach.Name='Unit Test Attachment';
    	Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
    	attach.body=bodyBlob;
        attach.parentId = acc.Id;
        insert attach;
        Test.startTest();
        Database.executeBatch(new ConvertAttachmenttoFile_Batch());
        Test.stopTest();
    }
}
What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
2
+1
0

You may also like

2 comments

subhrut September 1, 2023 - 7:18 am

please provide test class for above code

Reply
Rijwan Mohmmed September 1, 2023 - 10:23 am

Test class added.

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.