0
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LWCにContentVersionファイル一括ダウンロードする

Posted at

##LWCを利用して、Salesforceのコンテンツバージョンに登録される添付ファイルや画像を一括ダウンロードしてZIPファイルで圧縮する処理について、本文にて整理します。

LWC側のサンプルコード

bulkdownload.js
import { loadScript } from 'lightning/platformResourceLoader';
importjszipfrom'@salesforce/resourceUrl/jszip'
importFileSaverfrom'@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);
	    constevent=newShowToastEvent({
	        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);
	    constevent=newShowToastEvent({
	        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言語も利用できる。

0
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?