首页 > 解决方案 > 如何使用角度在 ts 文件中发送表单数据?

问题描述

我想使用表单数据类型将数据发送到后端。我想用html上传一张照片和名字,在上传成功的后端文件中,bur没有在前端取名字,我用postman检查了后端。这是完全有效的。

HTML 文件

<form  id="myForm">
     <label>Name</label>
     <input type="text" id="name" name="name" >
     <div>
         <input name="file" id="photo" type="file" accept="image/*" (change)="selectImage($event)" />
         <button type="button" (click)="upload()">Upload</button>
      </div>
</form>

类型脚本文件

export class AcademicsComponent implements OnInit {
  name;
  images;

  constructor(
    private http: HttpClient,
  ) { }

  ngOnInit() {

  }

  selectImage(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.images = file;
    }
  }
  upload() {
    this.name = name;
    const formData = new FormData();

    formData.append('profileImage', this.images)
    formData.append('name', this.name)

    const url = "http://localhost:3000/academics/uploadfile";

    this.http.post(url,formData).subscribe(res => {
      console.log(res)
    });
  }
}

后端响应

{ fieldname: 'profileImage',
  originalname: '19682.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'uploads/',
  filename: '19682.png',
  path: 'uploads\\19682.png',
  size: 1111883 }
{ _id: 5da03efb74492c3f8891c93f,
  path: '/uploadfile/19682.png',
  name: '',
  __v: 0 }

标签: angulartypescriptform-data

解决方案


您没有将输入中的名称值绑定到任何东西。

例如,您可以为此使用两种方式的数据绑定。

<form  id="myForm">
     <label>Name</label>
     <input type="text" id="name" name="name" [(ngModel)]="name">
     <div>
         <input name="file" id="photo" type="file" accept="image/*" (change)="selectImage($event)" />
         <button type="button" (click)="upload()">Upload</button>
      </div>
</form>

然后像这样上传

upload() {    
    const formData = new FormData();

    formData.append('profileImage', this.images)
    formData.append('name', this.name)

    const url = "http://localhost:3000/academics/uploadfile";

    this.http.post(url,formData).subscribe(res => {
      console.log(res)
    });
  }

推荐阅读