我正在构建MEAN Shop应用程序,试图将产品图像存储在mongodb中,但是会出现一些错误
typeError: cannot read the property 'productimage' of undefined
这是添加产品的路线功能
function addProduct(req, res, next){
var newProduct = new Product({
productName: req.body.productname,
productCategory: req.body.productcategory,
productDescription: req.body.productdescription,
productPrice: req.body.productprice
});
newProduct.productImage.data = fs.readFileSync(req.file.productimage);
newProduct.productImage.contentType = 'jpg';
newProduct.save(function(err){
if(err){
console.log("error saving product");
res.status(400).json({
success: false,
message:'Error processing request '+ err});
}
else{
console.log("product inserted");
res.status(201).json({
success: true,
message: 'Product added successfully.'
});
}
});
}
module.exports = {addProduct);
这是产品型号
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
productname : { type: String },
productCategory: { type: String },
productDescription: { type: String },
productImage: { data: Buffer, contentType: String },
productPrice: { type: Number }
});
module.exports = mongoose.model('product', productSchema, 'products');
这是html文件
<form class="form-style-9"
[formGroup]="productForm"
(ngSubmit)="addProduct(productForm.value)"
enctype="multipart/form-data"
>
<ul>
<li><span>Product Name</span>
<input type="text" name="productname" class="field-style field-full align-none" placeholder="Name" formControlName="productname" />
</li>
<span>Product Category</span><br>
<select formControlName="productcategory">
<option value="Clothing">Clothing</option>
<option value="Electronics">Electronics</option>
<option value="Books">Books</option>
<option value="Toys">Toys</option>
</select>
<li><span>Product Description</span>
<textarea name="productdescription" class="field-style" placeholder="Product Description" formControlName="productdescription"></textarea>
</li>
<li><span>Product Image</span>
<input type="file" name="productimage" class="field-style field-full align-none" placeholder="Image" formControlName="productimage"/>
</li>
<li><span>Product Price</span>
<input type="number" name="productprice" class="field-style field-full align-none" placeholder="Product Price" formControlName="productprice" />
</li>
<li>
<input type="submit" value="Add Product" />
</li>
</ul>
</form>
这是组件文件
export class ProductComponent implements OnInit {
constructor(private fb: FormBuilder,
private router: Router,
private productService: ProductService,
private toastr: ToastrService) { }
ngOnInit() {
}
productName = new FormControl("");
productCategory = new FormControl("");
productDescription = new FormControl("");
productImage = new FormControl("");
productPrice = new FormControl("");
productForm: FormGroup = this.fb.group({
'productname': this.productName,
'productcategory': this.productCategory,
'productdescription': this.productDescription,
'productimage': this.productImage,
'productprice': this.productPrice,
});
addProduct(formdata:any) {
this.productService.addProduct(this.productForm.value)
.subscribe(data => {
if (data.success === false) {
this.toastr.error(data.message);
} else {
this.toastr.success(data.message);
this.router.navigate([' ']);
}
this.productForm.reset();
});
}
}
我尝试使用 multer
,但是我不认为它可以正常工作,或者可能是我在编写错误的代码。请纠正我我在做什么错。
我创建了另一个文件夹来存储图像server/public/images
,该文件夹包含路径和模型server/models/
和server/routes/
。
这是服务器文件。
var multer = require('multer');
var app = express();
var api = require('./server/routes/api');
var image = multer({ dest:'./server/public/' });
app.post('/product', image.single('images'), api.addProduct);
我在这里做什么错了?
答案 0 :(得分:0)
我认为您的multer配置有问题。 您是否也可以共享您的需求和混合中间件。
我还在下面提供了一个示例配置,用于配置multer中间件。
const multer = require('multer')
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './path/to/file')
},
filename: (req, file, cb) => {
cb(null, "PDFS-"+file.originalname.substring(0, file.originalname.lastIndexOf('.')) + '-' + Date.now()+(path.extname(file.originalname)).toLowerCase())
}
});
var upload = multer({
storage: storage,
fileFilter: function (req, file, callback) {
var ext = (path.extname(file.originalname)).toLowerCase();
if(ext !== '.pdf') {
return callback(new Error('Only pdf format files are allowed!'))
}
callback(null, true)
},
limits:{
fileSize: 1024*1024
}
});
app.post('/upload', function(req, res, next){
upload.single('productimage')(req, res, function (err) {
if (err) {
console.log("upload err"+err);
res.render('upload');
return;
}
else{
if (req.file===undefined) {
console.log("empty");
res.render('upload');
}
else{
console.log("done");
res.render('upload');
}
}
});
});