node.js - 上传文件时 Multer 出现意外的字段错误
问题描述
嗨,我想创建一个带有 react 和 express 的文件上传 API。所以,我用了集合。但是当我从客户端发送到轴请求时,我从服务器收到错误消息。
错误:
MulterError:意外的字段
我的 Express 服务器代码是这样剪断的:
const storage = multer.diskStorage({
destination : '/',
filename(req,file,cb){
const newFileName = `${uuid()}-${file.originalname}`
cb(null,newFileName);
}
})
const uploadVideoFile = multer({
storage : storage
}).single("videofile");
app.post('/upload', uploadVideoFile, (req,res)=>{
if(req.file){
const filename = req.file.filename;
const {title , description} = req.body;
open(oAuth.generateAuthUrl({
access_type : 'offline',
scope : 'https://googleapis.com/auth/youtube.upload',
state : JSON.stringify({
filename, title, description
})
}))
}
})
我的反应客户是这样的:
const[form,setForm] = React.useState({
title : "",
description : "",
file : null
})
function handleChange(event){
const inputValue = event.target.name === "file" ? event.target.files[0] : event.target.value;
setForm({
...form,
[event.target.name] : inputValue
})
}
function handleSubmit(event){
event.preventDefault();
const videoData = new FormData();
videoData.append("videoFile", form.file);
videoData.append("title", form.title);
videoData.append("description", form.description);
axios.post('http://localhost:3000/upload', videoData).then(response=>{
console.log(response.data)
})
}
return (
<div>
<h1>Youtube Upload Service</h1>
<form onSubmit={handleSubmit}>
<div>
<input onChange={handleChange} type="text" name="title" autoComplete="off" placeholder="Title"/>
</div>
<div>
<textarea onChange={handleChange} type="text" name="description" autoComplete="off" placeholder="Description"/>
</div>
<div>
<input onChange={handleChange} accept="video/mp4" type="file" name="file" placeholder="Video File"/>
</div>
<button type="submit">Upload Video</button>
</form>
</div>
)
}
为什么我会收到此错误?我该如何解决这个问题?
解决方案
当 Multer 看到一个文件时,它会检查文件输入的名称是否与您配置的完全匹配。它也区分大小写。
您已将 Multer 配置为接受名为 "videofile": 的单个文件输入.single("videofile")
。但是,在前端,您将其命名为“videoFile”(大写 F)videoData.append("videoFile", form.file);
:. 由于 "videofile" !== "videoFile",Multer 抛出了一个意外的字段错误。
重命名两者中的任何一个以匹配另一个应该可以解决您的问题。要了解 Multer 的工作原理以及将来如何避免此错误,我建议阅读这篇文章:修复 Multer 的“意外字段”错误
推荐阅读
- android - ViewHolder 中 ImageView 的位置使用 .getLeft() 返回 0。如何在 ViewHolder 中获取 ImageView 的位置
- excel-formula - PowerBI - 用本周计算上周数据
- python - Python based on .txt file
- java - 在 Postman 中工作的 HTTP 查询在 Spring Boot Apache Camel 3.1 中不起作用
- python - 如何让我的代码使用定义的函数验证文件中的每一行
- javascript - 如何将我的 react js 类组件转换为功能组件?
- android - 使用 Kotlin 从我的模型类中保存 SharedPreference 中的值
- c# - C#在web api上实现一个接口
- php - iis 10 奇怪的行为 http 与 https - php 刷新 - responseBufferLimit 为 0
- javascript - 在 wordpress 中使用拉伸行和内容、拉伸行和内容(无填充)时,猫头鹰 Carousel2 图像不显示全宽