使用环回下载文件 4

Download File with loopback 4

我想从基于 loopback 4 的服务器下载文件。我目前的情况是,我可以使用 fs.readFileSync 访问该文件,但它仅适用于 text-files。如果我想下载 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 注入构造函数,我可以访问响应 object 并且可以使用 setHeader 方法编辑 headers,但是没有影响。

我需要做什么:

  1. 将文件内容正确传递给客户端
  2. 设置 headers 以告知浏览器正确的文件元数据

使用this.response.download()

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

    // your logic ...

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