##LWCを利用して、Salesforceのコンテンツバージョンに登録される添付ファイルや画像を一括ダウンロードしてZIPファイルで圧縮する処理について、本文にて整理します。
LWC側のサンプルコード
bulkdownload.js
import { loadScript } from 'lightning/platformResourceLoader';
import jszip from '@salesforce/resourceUrl/jszip'
import FileSaver from '@salesforce/resourceUrl/FileSaver'
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getAttachedFiles from '@saleforce/apex/BulkdownloadCtrl.getAttachedFiles';
初期表示時、JSロード処理とデータ取得処理を行う。
connectedCallback() {
console.log('* connectedCallback');
Promise.all([
// 初期表示処理
getAttachedFiles({ recordId : this.recordId}),
// JSZIP、FileSaverのJSプラグインをロードする。
loadScript(this, jszip),
loadScript(this, FileSaverNew)
])
.then(result => {
// 初期表示処理
// do something
})
.catch(error => {
// Error
this.showExceptionToast(error.body.message);
const event = new ShowToastEvent({
title: 'messageTitle',
message: error.body.message,
variant: 'error',
mode: 'sticky'
});
this.dispatchEvent(event);
});
}
/*
添付ファイルを取得して、ファイルを圧縮する処理
※ここがファイル毎に非同期処理を実行して、ファイルを取得する理由について、一括で複数ファイルを取得して12MB、ヒープサイズガバナ制限(12MB)が抵触するため。
*/
let zip = new JSZip();
let zipCount = 0; // 取得したファイル数
let zipFileName = 'testZipFile'; // ZIPファイル名
// 初期表示時に取得されたコンテンツバージョンID Listに基づいて、ループ処理を行う。
for(let i = 0; i < contentVersionIdList.length; i++) {
let _cvId = contentVersionIdList[i];
// コンテンツバージョンIDにより、非同期処理を呼出し、コンテンツバージョン情報を取得する。
getAttachedFile({"contentVersionId": _cvId})
.then(result => {
// 取得したファイル情報をJSZIPに設定する。
zip.file(result[0], result[2], {base64: true});
zipCount = zipCount + 1;
// 処理件数が最後となる場合、JSZIPをローカルに保存する。
if (zipCount == contentVersionIdList.length) {
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, zipFileName);
});
}
})
.catch(error => {
// Error
this.showExceptionToast(error.body.message);
const event = new ShowToastEvent({
title: 'messageTitle',
message: error.body.message,
variant: 'error',
mode: 'sticky'
});
this.dispatchEvent(event);
});
}
Apex側のサンプルコード
BulkdownloadCtrl.cls
@AuraEnabled(cacheable=false)
public static List<String> getAttachedFile(Id contentVersionId) {
ContentVersion cv = [SELECT Id, PathOnClient, VersionData, Title, FileExtension FROM ContentVersion
WHERE Id =: contentVersionId AND IsLatest = true limit 1];
List<String> result = new List<String>();
result.add(cv.PathOnClient);
result.add(EncodingUtil.base64Encode(cv.VersionData));
return result;
}
コード説明
添付ファイル一括ダウンロードできるキーポイントはファイル圧縮「JSZIP」、ファイル保存「FileSaver」のインポートです。
◆JSZIPのサンプルコードとソースのダウンロードは以下のリンクを参照する。
https://stuk.github.io/jszip/
◆FileSaverのサンプルコードとソースのダウンロードは以下のリンクを参照する。
https://github.com/eligrey/FileSaver.js
※JSZIP、FileSaverのプラグインはJSの共通のため、LWCだけでなく、ほかのWEB言語も利用できる。