上传 PDF 文件到 Express 服务器

eri*_*gio 5 node.js express multer axios

我已经构建了一个基本的浏览器表单,允许用户上传 PDF 文件。然后我想将该文件发送到 Express 后端。看起来这应该是一个非常基本的操作,但我不熟悉端到端流程,所以我不确定哪个部分失败了。我搜索了许多 SO 问题/答案,但没有找到任何提供完整解决方案的问题,而且我也无法拼凑出解决方案。

更新:看起来文件正在到达服务器,但编码混乱。我的猜测是这FileReader.readAsText是错误的使用方法。FileReader.readAsBinaryString让我更接近一点,但仍然不太正确(并且已弃用)。FileReader.readAsArrayBuffer似乎可能是要走的路,但我不确定如何正确处理 Express 中的缓冲区。

客户端/浏览器

该表单是在 React 中构建的,并且只onChange在输入本身上使用一个处理程序。添加文件后,处理程序读取文件,将其添加到表单数据中,并将发布请求发送到服务器。

// React form
<input
  name="upload"
  onChange={this._handleUpload}
  type="file"
/>

_handleUpload = (e) => {
  const { files, name } = e.target;

  // Read the file
  const reader = new FileReader();
  reader.onload = (e) => {
    const file = e.target.result;

    // Now that we have the file's contents, append to the form data.
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', name);

    axios
      .post('/upload', formData)
      .then(res => {
        // Handle the response...
      })
      .catch(err => console.log(err));
  };

  // Reading as text. Should this be something else?
  reader.readAsText(files[0]);
}
Run Code Online (Sandbox Code Playgroud)

快递应用

express 应用使用multer中间件来处理上传:

const app = express();
const upload = multer({});

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.post('/upload', upload.any(), handleUpload);
Run Code Online (Sandbox Code Playgroud)

中间件

最后,我有自己的中间件,可以从 multer 获取文件。我只是通过将收到的文件写入磁盘来测试这件作品。它有内容,但不是可读的 PDF 文件。

const handleUpload = (req, res, next) => {
  // The file shows up on req.body instead of req.file, per multer docs.
  const { file } = req.body;

  // File is written, but it's not a readable PDF.
  const tmp = fs.writeFileSync(
    path.join(__dirname, './test.pdf'),
    file,
  );
}
Run Code Online (Sandbox Code Playgroud)

有没有我在这里明显错误的部分?例如:是否需要以特殊方式处理 PDF?有关将调试重点放在何处的任何提示?

Cha*_*nce 5

看看是否能解决您的问题。

_handleUpload = (e) => {
    const dataForm = new FormData();
    dataForm.append('file', e.target.files[0]);  
      axios
        .post('http://localhost:4000/test', dataForm)
        .then(res => {

        })
        .catch(err => console.log(err));      
}

render() {
  return (
    <div className="App">
      <input
      onChange={this._handleUpload}
      type="file"
      />    
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

服务器:

router.post('/test', upload.any(), (req, res) => {
    console.log(req.files)
    res.send({sucess: true})
})
Run Code Online (Sandbox Code Playgroud)

无需发送文件类型,multer 会为您识别名称和类型。