简体   繁体   English

均值堆栈:如何使用nodejs expressjs和angular 6在mongodb中存储图像?

[英]Mean Stack: How can I store image in mongodb with nodejs expressjs and angular 6?

I am building a MEAN Shop App, trying to store the product image in mongodb but some error is coming 我正在构建MEAN Shop应用程序,试图将产品图像存储在mongodb中,但是会出现一些错误

typeError: cannot read the property 'productimage' of undefined

This is the route function for adding product 这是添加产品的路线功能

 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); 

This is the product model 这是产品型号

 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'); 

This is the html file 这是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> 

this is component file 这是组件文件

 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(); }); } } 

I tried using multer but i dont think its working or may be i am coding it wrong. 我尝试使用multer但我不认为它有效,或者可能是我编码错误。 Please correct me what am i doing wrong. 请纠正我我在做什么错。

I had created a different folder for storing image server/public/images , this is the same folder that contains routes and models server/models/ and server/routes/ . 我创建了另一个文件夹来存储图像server/public/images ,这是包含路由和模型server/models/server/routes/文件夹。

This is the server file. 这是服务器文件。

 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); 

What am i doing wrong here? 我在这里做错了什么?

I think there is a problem with your multer configuration. 我认为您的multer配置有问题。 Can you share your require's and multer middleware as well. 您是否也可以共享您的需求和混合中间件。

Also I have included a sample configuration below to configure your multer middleware. 另外,我还在下面提供了一个示例配置,用于配置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'); } } }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM