2

ループバック 4 ベースのサーバーからファイルをダウンロードしたいと考えています。私の現在の状況では、fs.readFileSync でファイルにアクセスできますが、テキスト ファイルに対してのみ機能します。PDFまたはzipファイルをダウンロードしたいのですが、うまくいきません。

これは私がこれまでに持っているものです:

export class FileController
{
    constructor(
        @repository(FileRepository) public fileRepository: FileRepository
    ){}


    @get('/files/download/{id}')
    async download(@param.path.number('id') id: number): Promise<string>
    {
        const file = await this.fileRepository.findById(id);
        const filepath = file.FilePath;

        if(!fs.existsSync(filepath))
        {
            throw new HttpErrors.NotFound(`The File #${id} can not be delivered, because the file is missing.`);
        }
        else
        {
            // @todo set headers for content type, length and caching
            return fs.readFileSync(filepath,'utf8');
        }
    }
}

コンストラクターに挿入RestBindings.Http.RESPONSEすると、応答オブジェクトにアクセスでき、setHeader-Method を使用してヘッダーを編集できますが、影響はありません。

私は何をしなければなりませんか:

  1. ファイルの内容をクライアントに正しく渡す
  2. ヘッダーを設定して、ブラウザーに正しいファイル メタデータを伝える
4

1 に答える 1

2

使用this.response.download():

return await new Promise((resolve: any, reject: any) => {

    // your logic ...

    this.response.download(filepath, (err: any) => {
        if (err) reject(err);
        resolve();
    });
});

于 2019-09-18T07:29:47.357 に答える