我想从基于 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
注入(inject)构造函数,我就能够访问响应对象,并可能使用 setHeader
-Method 编辑 header ,但是没有影响。
我必须做什么:
- 将文件内容正确传递给客户端
- 设置 header 以告知浏览器正确的文件元数据
最佳答案
使用this.response.download()
:
return await new Promise((resolve: any, reject: any) => {
// your logic ...
this.response.download(filepath, (err: any) => {
if (err) reject(err);
resolve();
});
});
关于node.js - 下载带有环回的文件 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57958538/