发送 POST 请求
按照官方文档的解释,可以使用getBinary()函数发送POST请求:
import { getBinary } from 'tns-core-modules/http'
getBinary({
url: 'https://example.com/foo/bar/generate-pdf',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
content: JSON.stringify(someObject),
})
这里,someObject 是您要转换为 JSON 并发送到服务器的对象。
接收、转换和保存文件/PDF
响应将包含 PDF 或任何其他文件作为 ArrayBuffer。如问题中所述,File.writeSync() 方法需要 NSData (iOS) 和 ByteArray (Android)。因此,我们需要获取一个文件处理程序,转换我们的文件并将其保存到文件系统中。
import { getBinary } from 'tns-core-modules/http'
import { isAndroid } from 'tns-core-modules/platform'
import { File, knownFolders, path } from 'tns-core-modules/file-system'
getBinary({
url: 'https://example.com/foo/bar/generate-pdf',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
content: JSON.stringify(someObject),
}).then((buffer) => {
// Get file handler
const documentsFolder = knownFolders.documents()
const destination = path.join(documentsFolder.path, 'result.pdf')
const file = File.fromPath(destination)
// Convert buffer to byte array
let byteArray
if (isAndroid) {
byteArray = Array.create('byte', buffer.byteLength)
for (let i = 0; i < buffer.length; i++) {
byteArray[i] = new java.lang.Byte(buffer[i])
}
} else {
byteArray = NSData.dataWithBytesLength(buffer, buffer.byteLength)
}
// Save file
file.writeSync(byteArray, (error) => {
console.log(error)
});
})
为什么File.writeSync() 方法不能自动转换它对我来说是个奇迹。也许其他人可以解释一下!
显示 PDF
要显示 PDF,您可以使用nativescript-pdf-view。只需使用文件处理程序获取路径file.path 或destination 变量并将其传递给PDFView 组件的src 属性。这可能看起来像这样:
<template>
<Page>
<ActionBar title="PDF" />
<GridLayout rows="*" columns="*">
<PDFView :src="path" row="0" col="0" />
</GridLayout>
</Page>
</template>
<script lang="ts">
export default {
name: 'PdfViewer',
props: {
path: {
type: String,
required: true,
},
},
}
</script>
一定要安装插件,当然是先把元素引入Vue.js:
// main.ts
Vue.registerElement('PDFView', () => require('nativescript-pdf-view').PDFView)