使用 Node.js 和 JavaScript 从缓冲区渲染 PDF

Render PDF from buffer using Node.js and JavaScript

我的 files 对象在后端:

[{ Id: 3,
  UserId: 7,
  FileType: 'application/pdf',
  FileContent:
   <Buffer 25 50 44 46 2d 31 2e 33 0d 0a 25 e2 e3 cf d3 0d 0a 0d 0a 31 20 30 20 6f 62 6a 0d 0a 3c 3c 0d 0a 2f 54 79 70 65 20 2f 43 61 74 61 6c 6f 67 0d 0a 2f 4f ... >,
  FileName: '1',
  UserUploadId: 7 },
...]

我正在将此对象发送到视图:

res.render('dashboard/files/index',{'title': 'My files', 'my_files' : files})

在 HTML 上,我正在使用 handlebarsjs 渲染一个 table,每个文件包含一行,以及一个按钮,该按钮执行接收文件作为唯一参数的函数 Id

<table class="table">
    <thead class="thead-dark">
        <tr>
            <th scope="col">UserId</th>
            <th scope="col">View</th>
        </tr>
    </thead>
    <tbody>
        {{#each my_files}}
        <tr>
            <td>{{this.UserId}}</td>
            <td>
                <button onclick="viewPdf({{this.Id}})"></button>
            </td>
        </tr>
        {{/each}}
    </tbody>
</table>

在同一个文档中,使用 JavaScript,我试图获取对象的 FileContent 属性,但为此我需要在数组 my_filesId 参数搜索。

<script>
    function viewPdf(Id){
        var found_file = my_files.find(function(element) {
            return element.Id == Id;
        });

        console.log(found_file)
    }
</script>

但我收到此错误输出:

Uncaught ReferenceError: my_files is not defined at viewPdf (......:465) at HTMLButtonElement.onclick

所以,

JavaScript 运行 服务器端和浏览器端不同。您在浏览器中找不到已声明的服务器端变量,反之亦然。

一种在服务器和客户端之间共享变量的方法:

function viewPdf(Id){
    $.ajax('/getFiles', {
        success:function(my_files){
            // put logic here
        }
    })
}