最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

NodeJsExpress在浏览器中显示pdf文件

IT培训 admin 10浏览 0评论

NodeJs / Express在浏览器中显示pdf文件

我正在处理NodeJs / Express项目,并且需要在存储在的browesr pdf文件中显示

/ public / images

这里是相关的路由器代码:

router.post('/show_file', async (req,res)=>{
  try {
     let path = './public/images/1.pdf'
     var data =fs.readFileSync(path);
     res.contentType("application/pdf");
     res.send(data);
   } catch (err) {
     res.status(500)
     console.log(err)
     res.send(err.message)
   }
})

我没有收到任何错误,但是什么也没发生,即浏览器没有打开等。预先感谢您的指导。

回答如下:

我要做的第一个更改是删除async。它将用不必要的承诺弄乱代码。

[第二,我删除了捕获异常的需要,并使用fs.existsSync(path)验证了文件的存在。尽量不要经常出现异常。如果您知道某些情况可能引发异常,请对其进行测试。

最后,也是最重要的,我创建了文件的读取流,并将结果通过fs.createReadStream(path).pipe(res)用管道传输到响应。这样,客户端在读取文件时会收到文件,并且会保留您的内存。非常适合大文件。

读取文件可能会占用大量内存,因此将其全部加载到内存中是一种不好的做法。您只需要少量请求即可使您的计算机超载。

您可以阅读更多有关管道方法here的信息。

在此示例中,任何对/router/show_file的GET调用都将返回pdf。

const express = require('express')
const app = express()
const fs = require('fs')
const router = express.Router()

router.get('/show_file', (req, res) => {
    const path = './public/images/1.pdf'
    if (fs.existsSync(path)) {
        res.contentType("application/pdf");
        fs.createReadStream(path).pipe(res)
    } else {
        res.status(500)
        console.log('File not found')
        res.send('File not found')
    }
})

app.use('/router', router) // Here we pass the router to the app with a path

app.listen(9999, () => console.log('Listening to port 9999'))

NodeJs / Express在浏览器中显示pdf文件

我正在处理NodeJs / Express项目,并且需要在存储在的browesr pdf文件中显示

/ public / images

这里是相关的路由器代码:

router.post('/show_file', async (req,res)=>{
  try {
     let path = './public/images/1.pdf'
     var data =fs.readFileSync(path);
     res.contentType("application/pdf");
     res.send(data);
   } catch (err) {
     res.status(500)
     console.log(err)
     res.send(err.message)
   }
})

我没有收到任何错误,但是什么也没发生,即浏览器没有打开等。预先感谢您的指导。

回答如下:

我要做的第一个更改是删除async。它将用不必要的承诺弄乱代码。

[第二,我删除了捕获异常的需要,并使用fs.existsSync(path)验证了文件的存在。尽量不要经常出现异常。如果您知道某些情况可能引发异常,请对其进行测试。

最后,也是最重要的,我创建了文件的读取流,并将结果通过fs.createReadStream(path).pipe(res)用管道传输到响应。这样,客户端在读取文件时会收到文件,并且会保留您的内存。非常适合大文件。

读取文件可能会占用大量内存,因此将其全部加载到内存中是一种不好的做法。您只需要少量请求即可使您的计算机超载。

您可以阅读更多有关管道方法here的信息。

在此示例中,任何对/router/show_file的GET调用都将返回pdf。

const express = require('express')
const app = express()
const fs = require('fs')
const router = express.Router()

router.get('/show_file', (req, res) => {
    const path = './public/images/1.pdf'
    if (fs.existsSync(path)) {
        res.contentType("application/pdf");
        fs.createReadStream(path).pipe(res)
    } else {
        res.status(500)
        console.log('File not found')
        res.send('File not found')
    }
})

app.use('/router', router) // Here we pass the router to the app with a path

app.listen(9999, () => console.log('Listening to port 9999'))
发布评论

评论列表 (0)

  1. 暂无评论