您可以将其保存为内容版本,现在不推荐使用附件。
public with sharing class ContentVersionUtil {
public ContentVersionUtil() {
}
public static Id createDocument(Id parentId, String fileName, String data, Id contentDocumentId) {
ContentVersion versionData = new ContentVersion();
versionData.ContentLocation = 'S';
versionData.ContentDocumentId = contentDocumentId;
versionData.VersionData = Blob.valueOf(data);
versionData.Title = fileName;
versionData.PathOnClient = filename;
insert versionData;
ContentDocumentLink conDocLink = new ContentDocumentLink();
conDocLink.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = :versionData.Id].ContentDocumentId;
conDocLink.LinkedEntityId = parentId;
conDocLink.ShareType = 'V';
insert conDocLink;
return conDocLink.Id;
}
public static Id createDocument(Id parentId, String fileName, String data) {
return createDocument(parentId, fileName, data, NULL);
}
public static Id createDocumentafterformat(Id parentId, String fileName, String data) {
return createDocument(parentId, fileName, data, NULL);
}
}
测试类:
@isTest
public with sharing class ContentVersionUtilTest {
@TestSetup
static void makeData(){
Account acc = new Account (Name = 'Test Account');
insert acc;
Contact cont = new Contact (LastName = 'Raj', AccountId = acc.Id);
insert cont;
}
@isTest
static void test_content_version_creation_0 () {
Contact eachContact = [SELECT Id from Contact LIMIT 1];
ContentVersionUtil util = new ContentVersionUtil ();
Id conDocLinkId = ContentVersionUtil.createDocument(eachContact.Id, 'testFile', 'csv', 'Some important Data');
System.assertEquals(eachContact.Id, [SELECT Id, LinkedEntityId from ContentDocumentLink WHERE Id =: conDocLinkId].LinkedEntityId);
}
}