node.js - 使用 multer 上传文件
问题描述
我正在尝试制作一个 Web 应用程序,您可以使用 express 和 multer 上传文件,但我遇到的问题是没有上传文件并且 req.file 始终未定义。我检查了多个解决方案,但没有一个有效.
我的 reactjs 组件如下:
onSubmit(e) {
e.preventDefault();
const productData = {
name: this.state.name,
image: this.state.image,
description: this.state.description,
category: this.state.category,
quantity: this.state.quantity,
price: this.state.price
};
console.log(productData.image);
this.props.createProduct(productData, this.props.history);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
<form onSubmit={this.onSubmit} encType="multipart/form-data">
<UploadImage
name="image"
value={this.state.image}
onChange={this.onChange}
error={errors.image}
type="file"
info="Upload image of the product"
/>
<input
type="submit"
value="Submit"
className="btn btn-info btn-block mt-4"
/>
</form>
我的路由器文件如下:
const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
//Loading validation function
const validateProductInput = require("../../validation/product.js");
//Load product model
const Product = require("../../models/Product");
//@route GET api/products/test
//@desc Test product route
//@access public
router.get("/test", (req, res) => res.json({ msg: "Profile Works" }));
//Creating a multer API to upload images
const storage = multer.diskStorage({
destination: "../../uploads",
filename: function(req, file, cb) {
cb(
null,
file.fieldname + "." + Date.now() + path.extname(file.originalname)
);
}
});
//Init Upload
const upload = multer({
storage: storage
});
//@route Post api/products/add
//@desc Add product
//@access Private
router.post("/add", upload.single("image"), (req, res) => {
const { errors, isValid } = validateProductInput(req.body);
if (!isValid) {
//Return any erros with 400 status
return res.status(400).json(errors);
}
console.log("File: ", req.file);
Product.findOne({
name: req.body.name
}).then(product => {
if (product) {
errors.exist = "Item Already Exists";
return res.status(400).json(errors);
} else {
// let image_path = req.body.image;
// image_path = image_path.replace(
// /fakepath/g,
// "projects\\e-commerce\\MERN-eCommerce\\client\\src\\components\\dashboard\\images"
// );
const newProduct = new Product({
name: req.body.name,
image: req.body.image,
description: req.body.description,
category: req.body.category,
quantity: req.body.quantity,
price: req.body.price
});
newProduct
.save()
.then(product => res.json(product))
.catch(err => res.status(404).json());
}
});
});
//上传图片组件
const UploadImage = ({ name, value, type, error, info, onChange }) => {
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function() {
var fileName = $(this)
.val()
.split("\\")
.pop();
$(this)
.siblings(".custom-file-label")
.addClass("selected")
.html(fileName);
});
return (
<div className="custom-file">
<input
className={classnames(
"custom-file-input form-control form-control-lg",
{
"is-invalid": error
}
)}
name={name}
type={type}
value={value}
onChange={onChange}
/>
<label className="custom-file-label">Choose file</label>
{info && <small className="form-text text-muted">{info}</small>}
{error && <div className="invalid-feedback">{error}</div>}
</div>
);
};
UploadImage.propTypes = {
name: PropTypes.string.isRequired,
placeholder: PropTypes.string,
value: PropTypes.string.isRequired,
info: PropTypes.string,
error: PropTypes.string,
onChange: PropTypes.func.isRequired
};
export default UploadImage;
console.log("文件:", req.file); 总是给出 undefined 并且没有文件上传到上传目录
解决方案
推荐阅读
- mysql - 如果两列与 MySQL 不匹配,则删除一行
- visual-studio - 如何将 WIX 扩展添加到 Nuget 包以供 WIX 安装程序项目使用
- angular - 错误处理异步管道 - Angular
- android - 用于延迟数据库下载的 RecyclerView Adapter 中的 Android ViewModel
- c++ - 模板模板参数:以下示例中应用了什么规则
- html - CSS Grid 在 flexbox 内时不会增长
- python - 更改装饰器内的实例属性
- sql - 如何忽略完全重复的行,但在列中有重复是可以的?
- c# - SQL Server 列类型 time(7) 不会显示在 Crystal Reports 中
- reactjs - 在 React App 中获取损坏的图像