我想用Nodejs作为后端在Angular中创建博客组件, 博客结构包含:图片和说明,我想在一个事件中将其上传到后端(nodejs和mongodb)。
主要关注的问题是如何在单个事件中将图像及其描述一起上传到后端。
答案 0 :(得分:1)
这是一个简单的例子。
<form
[formGroup]="angForm" novalidate (submit)="createBlog(angForm)" enctype="multipart/form-data">
<div class="form-group">
<textarea class="form-control form-control-lg" placeholder="Create a post" formControlName="data" #data ></textarea>
</div>
<div class="form-group">
<inpu type="file" name="image" name="image" #image (change)="onFileSelect($event)"/>
</div>
<button type="submit class="btn btn-dark" [disabled]="angForm.pristine || angForm.invalid" > Submit</button>
</form>
这是一个简单的angular reactive form
,我们使用它来验证必填字段,并在更改输入值上定义了onFileSelect()
函数,该函数将用于保存formData
blog.ts文件
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
angForm: FormGroup;
//our constructor
constructor(
private fb: FormBuilder,
private http: HttpClient
) {
this.createForm();
}
//reactive form group and set validations for required field
createForm() {
this.angForm = this.fb.group({
data: [null, Validators.required],
image: [""]
});
}
createBlog(form) {
const formData = new FormData();
formData.append("image", this.angForm.get("image").value);
formData.append("data", this.angForm.get("data").value);
this.http
.post("http://localhost:3000/blog/create", formData)
.subscribe(res => {
console.log(res);
});
}
//on change event we append file to formdata
onFileSelect(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.angForm.get("image").setValue(file);
}
}
要在nodejs中保存文件,您需要使用multer
包,并使用body-Parser来保存文本数据
const multer = require("multer");
const upload = multer({ dest: "public/images/" }); //desired path to save file
//your post route to save data
router.post( "/create",upload.single("file"),(req, res) => {
if (req.file) {
//creating instance of new blog
const newBlog = new Blog({
desc: req.body.data,
image: req.file.filename
});
//save blog data and image name into db
newBlog.save().then(blog => {
res.json(blog);
// return response
});
} else throw "error";
}
);