2020-11-28 File Upload in Salesf
2020-11-28 本文已影响0人
古月的小七
文件上传功能 Salesforce有提供专门的组件,具体可以参考下面的链接:
https://developer.salesforce.com/docs/component-library/bundle/lightning-file-upload/documentation
具体实现方式为:这种情况通常是你在一个Object上去Upload文件,而这个Object的Record已经存在了。
<template>
<lightning-file-upload
label="Attach receipt"
name="fileUploader"
accept={acceptedFormats}
record-id={myRecordId}
onuploadfinished={handleUploadFinished}
multiple>
</lightning-file-upload>
</template>
import { LightningElement, api } from 'lwc';
export default class FileUploadExample extends LightningElement {
@api
myRecordId;
get acceptedFormats() {
return ['.pdf', '.png'];
}
handleUploadFinished(event) {
// Get the list of uploaded files
const uploadedFiles = event.detail.files;
alert("No. of files uploaded : " + uploadedFiles.length);
}
}
还有另一个情况是,你在upload文件之后,在去保存这条记录,而这时该记录还没有存在这个时候就需要我们使用其他组件并且在Apex里面做一些特殊处理了:
首先在组件上我们选用 Lightning input, 具体如下:
<lightning-input type="file" onchange={onFileUpload} name="uploadFile" label="Upload File"></lightning-input>
在JS里面的处理是如下,针对File的解析处理:
onFileUpload(event) {
if (event.target.files.length > 0) {
this.uploadedFiles = event.target.files;
console.log(' this.uploadedFiles ' + this.uploadedFiles);
this.fileName = event.target.files[0].name;
this.file = this.uploadedFiles[0];
}
this.fileReader = new FileReader();
this.fileReader.onloadend = (() => {
this.fileContents = this.fileReader.result;
let base64 = 'base64,';
this.content = this.fileContents.indexOf(base64) + base64.length;
this.fileContents = this.fileContents.substring(this.content);
console.log('this.fileContents ' + JSON.stringify(this.fileContents));
this.fileListsLocal.push({
file: encodeURIComponent(this.fileContents),
fileName: this.fileName,
lastModifiedDate: Date.now(),
createdBy: this.currentUserName,
FileType: this.fileName.lastIndexOf(".") < 0? 'UNKNOWN' : (this.fileName.substr((this.fileName.lastIndexOf(".") + 1), this.fileName.length)).toLocaleUpperCase(),
fileSize: this.formatFileSizeBinary(this.file.size),
iconType: this.fileName.lastIndexOf(".") < 0? 'unknown' : this.formatIconType((this.fileName.substr((this.fileName.lastIndexOf(".") + 1), this.fileName.length)))
});
console.log('this.fileListsLocal. ' + JSON.stringify(this.fileListsLocal));
if(this.fileListsLocal !== null && this.fileListsLocal.length > 0){
const selectedEvent = new CustomEvent('saveattachfiles', {
detail: {
fileInfoList: this.fileListsLocal
},
});
this.dispatchEvent(selectedEvent);
}
});
this.fileReader.readAsDataURL(this.file);
}
在Apex中,对该Record的保存逻辑为:
@AuraEnabled
public static void documentLinkwithTask(String taskId, String fileInfoList){
System.debug('taskId '+taskId);
try{
List<ContentVersion> contenList = new List<ContentVersion>();
List<FileWrapper> fileInfoList1 = (List<FileWrapper>)JSON.deserialize(fileInfoList,List<FileWrapper>.class);
for(FileWrapper wrapper: fileInfoList1){
System.debug('wrapper '+wrapper);
ContentVersion contentVersionRec = new ContentVersion();
contentVersionRec.Title = wrapper.fileName;
contentVersionRec.PathOnClient = '/' + wrapper.fileName;
contentVersionRec.FirstPublishLocationId = taskId;
// String base64Content = ( String ) JSON.deserialize(wrapper.file, String.class );
String base64File = EncodingUtil.urlDecode(wrapper.file, 'UTF-8');
contentVersionRec.VersionData = EncodingUtil.base64Decode(base64File);
contentVersionRec.IsMajorVersion = true;
contenList.add(contentVersionRec);
}
Insert contenList;
}catch (Exception e) {
//throw exception
//System.debug('e.getMessage()-->'+e.getMessage() +' - '+e.getStackTraceString());
throw new AuraHandledException('Something went wrong: '+e.getMessage() );
}
}
下面的逻辑为获得某对象上关联的所有文件的代码:
public static List<ContentDocument> getTaskRelatedFiles(String taskId){
try{
List<String> contentDocumentIds = new List<String>();
List<ContentDocumentLink> docLinks =
[SELECT ContentDocumentId,Id,IsDeleted,LinkedEntityId,ShareType,SystemModstamp,Visibility
FROM ContentDocumentLink WHERE LinkedEntityId =: taskId];
for(ContentDocumentLink docLink: docLinks){
contentDocumentIds.add(docLink.ContentDocumentId);
}
List<ContentDocument> documents =
[SELECT ContentAssetId,
ContentModifiedDate,
ContentSize,
CreatedById,
CreatedBy.Name,
CreatedDate,
Description,
FileExtension,
FileType,
Id,
IsDeleted,
LastModifiedById,
LastModifiedDate,
LastReferencedDate,
LastViewedDate,
LatestPublishedVersionId,
OwnerId,
PublishStatus,
Title
FROM ContentDocument
WHERE Id
IN: contentDocumentIds
];
return documents;
}catch(Exception e){
throw new AuraHandledException('Something went wrong: '+e.getMessage());
}
}