关于 node.js:我如何在 Angular 中写博客组件?

How can i blog component in Angular?

我想在Angular中制作一个以Nodejs为后端的博客组件,
博客结构包含:图像和描述,我想在单个事件中将其上传到后端(nodejs 和 mongodb)。

主要关注的是如何在一个事件中将图像及其描述一起上传到后端。


这是一个简单的例子。

1
2
3
4
5
6
7
8
9
10
<form
  [formGroup]="angForm" novalidate (submit)="createBlog(angForm)" enctype="multipart/form-data">
   
     <textarea class="form-control form-control-lg" placeholder="Create a post" formControlName="data" #data  ></textarea>
   
   
    <inpu type="file" name="image" name="image" #image (change)="onFileSelect($event)"/>
   
   <button type="submit class="btn btn-dark" [disabled]="angForm.pristine || angForm.invalid"> Submit</button>
 </form>

这是一个简单的 angular reactive form,我们用来验证所需的字段,我们定义了 onFileSelect() 函数来更改输入值,我们将使用它来保存 formData

blog.ts 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 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来保存文本数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 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";
  }      
);