javascript - 如何以相同的形式上传文件和文本输入?
问题描述
我正在尝试上传图像以及一些文本输入。(如果用户给出)
我已经这样写了我的表格
<form action="/user/upload" method="POST" enctype="multipart/form-data">
<input type="text" placeholder="Type Something" name="message" />
<input type="file" name="img" id="image" accept="image/*" />
<button type = "submit">SUBMIT</button>
</form>
在服务器端。我无法阅读res.body
我得到res.body
的ie null
。我能够管理上传的文件。但只有文本输入是问题。
有人可以帮我解决这个问题吗?
我正在使用express
withmulter
进行文件上传。这是我的服务器端代码。
const storage = multer.diskStorage({
// destination: "./public/posts/",
destination: (req, file, callback) => {
const imageFileTypes = /jpeg|jpg|png|gif/;
const videoFileTypes = /mp4/;
let storagePath;
if (imageFileTypes.test(path.extname(file.originalname))) {
storagePath = "./public/posts/";
return callback(null, storagePath);
} else if (videoFileTypes.test(path.extname(file.originalname))) {
storagePath = "./public/videos/";
return callback(null, storagePath);
} else {
callback("ERROR: Invalid File Type");
return;
}
},
filename: function (req, file, cb) {
// FIELD NAME IS THE NAME YOU ASSIGNED TO THE INPUT FIELD IN EJS FILE
cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname));
},
});
const upload = multer({
storage: storage,
// limits: {fileSize: 1000000}
fileFilter: (req, file, cb) => {
//CUSTOM FUNCTION TO CHOOSE ONLY IMAGE AND VIDO FILES
checkFileType(file, cb);
},
}).single("img");
const checkFileType = (file, cb) => {
const imageFileTypes = /jpeg|jpg|png|gif/;
const videoFileTypes = /mp4/;
//CHECK THE EXTENCTION
const isImageExtenction = imageFileTypes.test(path.extname(file.originalname).toLowerCase());
const isVideoExtenction = videoFileTypes.test(path.extname(file.originalname).toLowerCase());
//CHECK THE MIME TYPE
const isImageMimeType = imageFileTypes.test(file.mimetype);
const isVideoMimeType = videoFileTypes.test(file.mimetype);
if ((isImageExtenction && isImageMimeType) || (isVideoExtenction && isVideoMimeType)) {
return cb(null, true);
} else {
return cb("Invalid file type");
}
};
//**************************THIS IS THE UPLOAD ROUTE*************
router.post("/upload", async (req, res) => {
upload(req, res, err => {
if (err) {
res.send("file upload failed");
return;
} else {
// console.log(req.file);
console.log(req.body.name);
res.send("file uploaded");
}
});
});
解决方案
推荐阅读
- ramda.js - Ramda - 如何向嵌套对象添加新属性
- c++ - C++没有构造函数实例匹配参数列表e0289
- vue.js - vue 应用程序从客户端源(ip+port)而不是前端服务器调用后端
- flutter - 错误:无法从方法“pop”返回“void”类型的值,因为它的返回类型为“bool”
- node.js - this.isModified 在 findOneAndUpdate 预挂钩中不起作用?
- c# - MySQL 连接器 C#,MySQLDataRead.Read() 仅在返回值时运行
- typescript - id 字段是否应该是可选的?
- reactjs - IOS“添加到主屏幕”指向资产文件夹
- ios - 获取数组元素并移除
- javascript - 如何将输入值数据传递给Vue中的根元素?