支持堆栈溢出。 我从客户端向服务器发送一个请求,将其分成多个块(因为需要一个大的 pdf 文件,并且 cloudflare 在等待响应 100 秒后关闭通道)。 我通过 axios 发送请求并递增结果字符串(应该是 base64),然后应该从客户端下载该结果。 服务器完成工作后,出现以下错误:要解码的字符串未正确编码
客户端代码:
downloadFile(response: string, name: string, download = false) {
const data = response
const binaryString = window.atob(data)
const binaryLen = binaryString.length
const bytes = new Uint8Array(binaryLen)
for (let i = 0; i < binaryLen; i++) {
const ascii = binaryString.charCodeAt(i)
bytes[i] = ascii
}
const blob = new Blob([bytes], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.target = '_blank'
if (download) link.download = name
window.open(link.href)
link.click()
}
async downloadQrs(ids: number[], withQrs = true) {
const tmp = [...ids]
let data = ''
while (tmp.length) {
const chunk = tmp.splice(0, 20)
const req = await this.axios.get<string>('/printforms/orders', {
params: {ids: chunk, withQrs}
})
data += req.data
}
return this.downloadFile(data, 'orders.pdf', true)
}
服务器端代码:
//controller
@Get('orders')
async orders(
@Query('ids') ids: string[],
@Query('withQrs', ParseBoolPipe) withQrs: boolean,
) {
const pdf = await this.printforms.orders(
ids.map((id) => Number(id)),
withQrs,
)
return (Buffer.from(pdf).toString('base64'))
}
//service
async orders(ids: number[], withQrs = true) {
const orders = await this.prisma.order.findMany({
where: { id: { in: ids }, chrtId: { not: null } },
})
const shop = await this.prisma.shop.findUnique({
where: { id: orders[0].shopId },
})
const api = new WildberriesApi(this.prisma, shop.wbToken, shop.id)
const g = groupBy(orders, 'chrtId')
const arr = []
await fs.ensureDir('tmp')
const allLables: { orderId: number; file: string }[] = []
const orderQr = await api.getOrderQr(ids, 'svg')
allLables.push(...orderQr.stickers)
let i = 0
for (const key in g) {
console.log(i)
i++
const productPdf = await this.product(+key, g[key].length)
const filename1 = v4() + '.pdf'
await fs.writeFile('tmp/' + filename1, productPdf)
arr.push(filename1)
if (withQrs) {
const labels = allLables.filter((l) =>
g[key].some((o) => o.id === l.orderId),
)
for (const label of labels) {
const filename2 = v4() + '.pdf'
await fs.writeFile(
'tmp/' + filename2,
await this.svgToPdf(
Buffer.from(label.file, 'base64')
.toString('ascii')
.replace(' width="580" height="400"', ''),
),
)
arr.push(filename2)
}
}
}
const merger = new PDFMerger()
for (const fn of arr) {
await merger.add('tmp/' + fn)
await fs.remove('tmp/' + fn)
}
const mergedFilename = v4() + '.pdf'
await merger.save('tmp/' + mergedFilename)
const data = await fs.readFile('tmp/' + mergedFilename)
await fs.remove('tmp/' + mergedFilename)
return data
}
我的编码有什么问题吗?