2

我想从基于 loopback 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 回答