还有其他关于使用Angular 4上传图像的问题,但没有全面的答案。我玩过ng2-file-upload和angular2-image-upload,但无法将它们保存在我的Mongo / Mongoose数据库中。这就是我所要做的......
组件HTML:
<form (submit)="newProduct(formData)" #formData="ngForm">
<div class="form-group">
<label for="name">Product Name:</label><input type='text' name='name' class="form-control" id="name" ngModel>
</div>
<div class="form-group">
<label for="image">Image:</label><input type="file" name='image' class="form-control" id="image" ngModel>
</div>
<div class="form-group">
<label for="description">Description:</label><input type='text' name='description' class="form-control" id="description" ngModel>
</div>
<div class="form-group">
<label for="quantity">Quantity:</label><input type='number' name='quantity' class="form-control" id="quantity" ngModel>
</div>
<button type="submit" class="btn btn-default">Add</button>
</form>
&#13;
Component.ts
import { Component, OnInit } from '@angular/core';
import { AddService } from './add.service';
...
export class AddComponent implements OnInit {
constructor(private _addService:AddService) { }
ngOnInit() {
}
newProduct(formData){
this._addService.addProduct(formData.value)
.then(()=>{
formData.reset()
})
.catch(err=>console.log(err))
}
}
&#13;
Compoenent服务
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs';
@Injectable()
export class AddService {
constructor(private _http:Http) { }
addProduct(newprod){
return this._http.post('/api/newprod', newprod).map((prod:Response)=>prod.json()).toPromise();
}
}
&#13;
控制器
addProduct:(req,res)=>{
let newProd = new Product(req.body);
newProd.save((err,savedProd)=>{
if(err){
console.log("Error saving product");
} else {
res.json(savedProd);
}
})
},
&#13;
架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: {type:String,required:true},
image: {data:Buffer, contentType:String},
description: {type:String,required:true},
quantity: {type:Number,required:true},
}, {timestamps:true})
var Product = mongoose.model('Product', ProductSchema);
&#13;
所有其他输入使其恢复到数据库正常。我需要做些什么才能正确保存图像?
答案 0 :(得分:1)
恐怕你无法直接上传这样的图片。首先,您可以从文件标签访问图像数据并分配到formdata。
你可以这样试试。在你的组件中
newProduct(formData){
let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#image');
let fileCount: number = inputEl.files.length;
let formData = new FormData();
if (fileCount > 0) {
formData.append('image', inputEl.files.item(0));
}
this._addService.addProduct(formData.value)
.then(()=>{
formData.reset()
})
.catch(err=>console.log(err))
}
}
这不是确切的工作解决方案,但你可以这样开始。