我希望我的NestJS应用程序有一个端点从Sharepoint API下载文件。我已经这样做了,但它下载的文件在缓冲区,并在下载后,它发送回运行端点的客户端。
目前我的代码是这样的:
private async sharepointApi(url: string): Promise<Response> {
// Get authentificated
const authHeaders = await this.getAuthHeaders();
// If authentification failed, return undefined
if (authHeaders === undefined) {
console.error('Error while getting conntected');
return undefined;
}
// Get api result
return fetch(`${this.site.url}/_api/${url}`, {
headers: {
...authHeaders,
Accept: 'application/json;odata=verbose',
},
});
}
private async sharepointBufferApi(url: string): Promise<Buffer> {
const result = await this.sharepointApi(url);
return result.buffer();
}
async getFile(fileRelativeUrl = ''): Promise<Buffer> {
fileRelativeUrl = this.transformServerRelativeUrl(fileRelativeUrl);
// Get file as a Buffer from Sharepoint
const spFile = this.sharepointBufferApi(
`web/GetFileByServerRelativeUrl('${encodeURIComponent(
fileRelativeUrl,
)}')/$value`,
);
return spFile;
}
所以这段代码,等待我的NestJS应用程序下载文件。只有当它下载,它发送回客户端。我想知道是否有可能发送它“活”没有等待下载。因为对于一个700 Mb的样本文件,我需要一段时间才开始下载它,当我点击端点下载...
提前感谢您的任何回复!
1条答案
按热度按时间a0zr77ik1#
日安!
你需要使用流。看看official NestJS documentation。
由于您不是从
fs
读取文件,因此需要将Buffer
转换为可读流:那么你可以:
这种方法将允许您在不使系统过载的情况下流式传输大量文件。
如果您想了解更多关于NodeJS中的流,请查看this YouTube video
希望能有所帮助!