首页 > 解决方案 > 无法使用 nodejs 和 express 获取文件上传功能

问题描述

我有一个 enctype 设置为多部分表单数据的表单,它有一个文件上传输入,还有其他文本输入字段。我确实在发布请求中看到表单与上传的文件一起作为多部分发送。我尝试使用 multer 和 express-fileupload。尝试了所有不同的方法,我可以从与此相关的其他 stackoverflow 线程中尝试,但我无法在 req.files 中获取文件。它总是未定义的。我没有使用任何中间件。我只是使用我知道不解析多部分数据的 body-parser。是否有关于如何使用当前版本的 node 和 express 使文件上传与其他表单字段一起使用的示例?

标签: node.jsexpressfile-uploadmulter

解决方案


你可以试试:

安装 express 和 multer

npm install express multer

app.js 文件:

const express = require('express');
const app = express();
const multer = require('multer');


// dest -> which tells Multer where to upload the files
const upload = multer({dest:'uploads/'}).single("avatar");


app.post("/profile", (req, res) => {
   upload(req, res, (err) => {
    if(err) {
      res.status(400).send("There is a problem!");
    }
    res.status(200).json({file: req.file});
  });
});

app.listen(3000, () => { 
    console.log('Server is runnig on port 3000');
});

并运行服务器:

node app.js

在 Postman 地址栏中设置此 url:http://localhost:3000/upload-image 并且您可以在 Postman 中上传文件并检查响应。

您也可以在没有 Postman 的情况下在浏览器中上传文件。

<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>

阅读更多详细信息: 使用 multer doc 表达


推荐阅读