

上一篇我们开发了一个显示头像框的自定义组件,今天我们上边的基础上实现头像上传功能,前边我们利用【lightning-file-upload
】标签已经实现文件上传功能,但因为使用的是Lwc提供的标签,所以无法将按钮和label进行自定义,如下图。

使用【<input type="file">】标签,重新开发文件上传功能,因为没有使用Lwc提供的标签,DB存储操作需要在Apex类中实现。
fileUploaderLwc.html
<template>
<div class="slds-form-element slds-has-error">
<div class="slds-form-element__control">
<div class="slds-file-selector slds-file-selector_files">
<div class="slds-file-selector__dropzone">
<input type="file" class="slds-file-selector__input slds-assistive-text"
accept="image/jepg" id="file-upload-input-123"
aria-describedby="error-124"
onchange={openfileUpload}
aria-labelledby="file-selector-primary-label-121 file-selector-secondary-label122" />
<label class="slds-file-selector__body" for="file-upload-input-123" id="file-selector-secondary-label122">
<span>Upload</span>
</label>
</div>
</div>
</div>
</div>
</template>fileUploaderLwc.js
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import uploadFile from '@salesforce/apex/FileUploaderController.uploadFile'
export default class FileUploaderLwc extends LightningElement {
@api recordId;
fileData
openfileUpload(event) {
const file = event.target.files[0]
var reader = new FileReader()
reader.onload = () => {
var base64 = reader.result.split(',')[1]
this.fileData = {
'filename': file.name,
'base64': base64,
'recordId': this.recordId
}
console.log('>>>>>111::'+this.fileData);
this.handleClick();
}
reader.readAsDataURL(file);
// const {base64, filename, recordId} = this.fileData
// uploadFile({ base64, filename, recordId }).then(result=>{
// this.fileData = null
// let title = `${filename} uploaded successfully!!`
// this.toast(title)
// })
}
handleClick(){
console.log('>>>>>>>>>>>>>>>>>this.fileData>>::'+this.fileData);
const {base64, filename, recordId} = this.fileData
uploadFile({ base64, filename, recordId }).then(result=>{
this.fileData = null
let title = `${filename} uploaded successfully!!`
this.toast(title)
})
}
toast(title){
const toastEvent = new ShowToastEvent({
title,
variant:"success"
})
this.dispatchEvent(toastEvent)
}
}FileUploaderController.cls
public with sharing class FileUploaderController {
/*
* @method uploadFile()
* @desc Creates a content version from a given file's base64 and name
*
* @param {String} base64 - base64 string that represents the file
* @param {String} filename - full file name with extension, i.e. 'products.csv'
* @param {String} recordId - Id of the record you want to attach this file to
*
* @return {ContentVersion} - returns the created ContentDocumentLink Id if the
* upload was successful, otherwise returns null
*/
@AuraEnabled
public static String uploadFile(String base64, String filename, String recordId) {
ContentVersion cv = createContentVersion(base64, filename);
ContentDocumentLink cdl = createContentLink(cv.Id, recordId);
if (cv == null || cdl == null) { return null; }
return cdl.Id;
}
/*
* @method createContentVersion() [private]
* @desc Creates a content version from a given file's base64 and name
*
* @param {String} base64 - base64 string that represents the file
* @param {String} filename - full file name with extension, i.e. 'products.csv'
*
* @return {ContentVersion} - returns the newly created ContentVersion, or null
* if there was an error inserting the record
*/
private static ContentVersion createContentVersion(String base64, String filename) {
ContentVersion cv = new ContentVersion();
cv.VersionData = EncodingUtil.base64Decode(base64);
cv.Title = filename;
cv.PathOnClient = filename;
try {
insert cv;
return cv;
} catch(DMLException e) {
System.debug(e);
return null;
}
}
/*
* @method createContentLink() [private]
* @desc Creates a content link for a given ContentVersion and record
*
* @param {String} contentVersionId - Id of the ContentVersion of the file
* @param {String} recordId - Id of the record you want to attach this file to
*
* @return {ContentDocumentLink} - returns the newly created ContentDocumentLink,
* or null if there was an error inserting the record
*/
private static ContentDocumentLink createContentLink(String contentVersionId, String recordId) {
if (contentVersionId == null || recordId == null) { return null; }
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = [
SELECT ContentDocumentId
FROM ContentVersion
WHERE Id =: contentVersionId
].ContentDocumentId;
cdl.LinkedEntityId = recordId;
// ShareType is either 'V', 'C', or 'I'
// V = Viewer, C = Collaborator, I = Inferred
cdl.ShareType = 'V';
try {
insert cdl;
return cdl;
} catch(DMLException e) {
System.debug(e);
return null;
}
}
}
文件上传组件开发完成,引入到之前的头像框显示组件之中。
accountInfo.html
<c-file-uploader-lwc
record-id={recordId}
></c-file-uploader-lwc>
效果展示:


与标准组件一样数据存储到相应DB之中。
SELECT Id, LinkedEntityId, ContentDocumentId, IsDeleted,
SystemModstamp, ShareType, Visibility
FROM ContentDocumentLink where LinkedEntityId = '0015g00000CUDdRAAX'
SELECT Id, CreatedById, ArchivedDate, IsDeleted, OwnerId,
SystemModstamp, Title, PublishStatus, LatestPublishedVersionId,
ContentSize, FileType FROM ContentDocument where Id in ('0695g000005da0PAAQ')
SELECT Id, ContentDocumentId, IsLatest, ContentUrl, ContentBodyId,
VersionNumber, Title
FROM ContentVersion where ContentDocumentId in ('0695g000005da0PAAQ')
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。