PDF 在node.js 中显示为缓冲区对象。我如何将其解析为文本?

问题描述 投票:0回答:1

我是在后端处理文件的新手。我正在尝试将 pdf 发送到后端,然后我想解析 pdf 以便我可以阅读其文本。看来我可以将pdf发送到后端。但是,我不知道在后端获取pdf文本后如何阅读它。这是我的发帖请求:

app.post("/submitPDF", (request, response)=>{
  console.log("Made a post request>>>", request.body);

  // if (!request.files && !request.files.pdfFile) {
  //   console.log("No file received");
  //   response.status(400);
  //   response.end();
  // }
  pdfParse(request.body.pdfFile).then((result) =>{
    console.log(result.text);
  });
  response.status(201).send({message: "File upload successful"});
});

这是我的 api post 请求,只是为了展示我如何发送 pdf。我创建了一个

FormData
对象,附加了我的 pdf,然后将其发送到我的帖子请求中:

export const fetchPDF = (value) => {

    console.log("The value>>>",value);
    const formData = new FormData();
    formData.append('pdfFile',value);
    console.log(Object.fromEntries(formData.entries())) //this is how to console log items in FormData

    return fetch(`${baseURL}/submitPDF`,{
        method:'POST',
        headers:{
            'Content-Type': 'multipart/form-data', ///had to change content-type to accept pdfs. this fixed the cors error
        },
        body:formData
    })
    .then((response)=>{
        if(response.ok){
            console.log("The response is ok");
            return response;
        }
        else{
            // If not successful, handle the error
            console.log("the response is not ok",response);
            throw new Error(`Error: ${response.status} - ${response.statusText}`);
        }
    })
    .catch((error)=>{
        console.log("There is an error>>>",error.message);
    })
}

当我console.log包含pdf的request.body时,我得到一些像这样的Buffer对象:

发出帖子请求>>> 72 6d 42 6f 75 6e 64 61 72 79 35 57 69 37 45 36 4f 31 49 36 37 45 6f 53 42 >32 0d 0a 43 6f 6e 74 65 6e 74 2d ... 120更多字节>

我尝试使用 pdf-parse 来解析我的 pdf,如下所示:

pdfParse(request.body.pdfFile).then((result) =>{
    console.log(result.text);
  });

但是我收到这两个错误:

throw new Error('getDocument 中的参数无效,' + '需要 >Uint8Array、字符串或参数对象');

错误:getDocument 中的参数无效,需要 Uint8Array、字符串或参数对象

看来我必须解析缓冲区对象,但我不确定我到底是如何做到的?我是否必须将缓冲区对象转换为字符串?如果是这样,我该怎么做?然后我使用 pdf-parse 然后我可以阅读 pdf 的文本?

非常感谢任何帮助!预先感谢!

node.js express pdf react-redux
1个回答
0
投票

您需要一些中间件来上传文件。

Multer 推荐例如: https://github.com/expressjs/multer

然后将您的代码更新为:

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
    // req.file is the `avatar` file
    // req.body will hold the text fields, if there were any
})
© www.soinside.com 2019 - 2024. All rights reserved.