如何使用角度发送ts文件中的表格数据?

问题描述 投票:0回答:2

我想使用表单数据类型将数据发送到后端。我想使用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 }
angular typescript form-data
2个回答
3
投票

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

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

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

1
投票

请先使用FormBuilder和FormGroup,然后附加数据。

export class UploadFile {

 uploadForm: FormGroup;

 this.uploadForm = this.formBuilder.group({
      profile: ['']
    });
const formData = new FormData();
    formData.append('file', this.uploadForm.get('profile').value);
}
© www.soinside.com 2019 - 2024. All rights reserved.