【发布时间】:2019-04-29 11:39:35
【问题描述】:
我尝试使用 NestJs 从控制器端点返回 PDF 文件。当不设置Content-type 标头时,getDocumentFile 返回的数据会很好地返回给用户。然而,当我添加标题时,我得到的返回似乎是某种奇怪形式的 GUID,响应总是如下所示:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 其中x 是一个小写的十六进制字符。它似乎也与处理函数的实际返回值完全无关,因为我什至在根本不返回任何东西时都会得到这个奇怪的 GUID。
当不设置Content-type: application/pdf 时,函数返回缓冲区的数据就好了,但是我需要设置标题以使浏览器将响应识别为PDF 文件,这对我的用例很重要。
控制器如下所示:
@Controller('documents')
export class DocumentsController {
constructor(private documentsService: DocumentsService) {}
@Get(':id/file')
@Header('Content-type', 'application/pdf')
async getDocumentFile(@Param('id') id: string): Promise<Buffer> {
const document = await this.documentsService.byId(id)
const pdf = await this.documentsService.getFile(document)
// using ReadableStreamBuffer as suggested by contributor
const stream = new ReadableStreamBuffer({
frequency: 10,
chunkSize: 2048,
})
stream.put(pdf)
return stream
}
}
我的 DocumentsService 是这样的:
@Injectable()
export class DocumentsService {
async getAll(): Promise<Array<DocumentDocument>> {
return DocumentModel.find({})
}
async byId(id: string): Promise<DocumentDocument> {
return DocumentModel.findOne({ _id: id })
}
async getFile(document: DocumentDocument): Promise<Buffer> {
const filename = document.filename
const filepath = path.join(__dirname, '..', '..', '..', '..', '..', 'pdf-generator', 'dist', filename)
const pdf = await new Promise<Buffer>((resolve, reject) => {
fs.readFile(filepath, {}, (err, data) => {
if (err) reject(err)
else resolve(data)
})
})
return pdf
}
}
我最初只是返回了缓冲区 (return pdf),但这带来了与上述尝试相同的结果。在 NestJs 的存储库中,一位用户建议使用上述方法,这显然对我也不起作用。请参阅 GitHub 线程 here。
【问题讨论】:
-
没有错误,但是,如上所述,我没有得到 PDF 数据作为返回,而是一个看似随机的 GUID(顺便说一句,每个请求都不同)。没有任何错误消息,显然不是我想要的结果
-
你找到解决办法了吗?
-
很遗憾没有。你有同样的问题吗?
-
不相似,但我无法使用 axios 从 React App 下载文件。我得到的只是空的 blob 数据或此输出
<Buffer 25 50 44 46 ... >
标签: javascript node.js nestjs