node.js - 无法使用 nodejs 和 express 获取文件上传功能
问题描述
我有一个 enctype 设置为多部分表单数据的表单,它有一个文件上传输入,还有其他文本输入字段。我确实在发布请求中看到表单与上传的文件一起作为多部分发送。我尝试使用 multer 和 express-fileupload。尝试了所有不同的方法,我可以从与此相关的其他 stackoverflow 线程中尝试,但我无法在 req.files 中获取文件。它总是未定义的。我没有使用任何中间件。我只是使用我知道不解析多部分数据的 body-parser。是否有关于如何使用当前版本的 node 和 express 使文件上传与其他表单字段一起使用的示例?
解决方案
你可以试试:
安装 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 表达
推荐阅读
- python - PyGame - 带有阴影的文本
- powershell - 用于查询属于某个组名及其变体的所有用户的 powershell 脚本
- networking - Ansible 循环 Ansible_net_interfaces 没有看到 item.key 的定义
- algorithm - 将数组拆分为权重相似的子数组
- javascript - 根据某些因素使 settimeout 不同
- c++ - 按需渲染帧
- c# - 删除两行之间的文本
- php - 为什么 php in_array 对不匹配的字符串值返回 true?这是一个错误吗?
- javascript - chrome显示Uncaught TypeError:尝试获取最后一行第一个单元格值时无法读取null的属性“单元格”
- python - 空白计数器