繁体   English   中英

如何使用 FormData 以角度放置请求?

[英]how to use FormData for put request in angular?

我试图使用角度反应形式在服务器上上传文件。当我尝试编辑生成错误内部服务器错误的表单时,但是当我使用邮递员成功更新文件时,我不知道我的FormData put 请求中缺少什么? 发布请求成功

addteacher.component.html

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators ,FormGroup,FormArray,FormControl} from '@angular/forms'
import { TeacherServiceService } from '../shared/teacher/teacher-service.service';
import {ActivatedRoute,Router} from '@angular/router';
import {Teacher} from '../shared/teacher/teacher';



@Component({
  selector: 'app-addteacher',
  templateUrl: './addteacher.component.html',
  styleUrls: ['./addteacher.component.css']
})
export class AddteacherComponent implements OnInit {
  teacherform:FormGroup;
  teacher: Teacher;
  FormTitle:String;





  constructor(private fb: FormBuilder,
    private teacherService: TeacherServiceService,
    private route : ActivatedRoute,
    private router : Router

    ) { }



  ngOnInit() {

    this.teacherform = this.fb.group({
      t_p_img: [''],
      t_id: [''],
      t_name: [''],
      t_desig: [''],
      t_dob: [''],
      t_pswd: [''],
      t_email: ['',[Validators.required]],
      t_gender: [''],
      t_phone: [''],
      t_quali: [''],
      t_address: ['']
       });


//Getting Teacher id
    this.route.paramMap.subscribe(params=>{
      const techId = params.get('id');
      if(techId){
        this.FormTitle = "Update Teacher Form";

       this.getTeacherr(techId);
      }
      else{
        this.FormTitle = "Teacher Registration Form";
        this.teacher = {
          t_id:null,
          t_name:'',
          t_desig: '',
          t_dob:null,
          t_email:'',
          t_pswd:'',
          t_gender:'',
          t_phone:null,
          t_quali:'',
          t_p_img:'',
          t_address:'',
          _id:null,
          courses:[]
        }
      }
    });

  }//
  selectedFile(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.teacherform.get('t_p_img').setValue(file);
    }
  }


  saveRecord():void {
    var formData:any = new FormData();
    var t_p_image = this.teacherform.value.t_p_img;
    var t_email = this.teacherform.value.t_email;
    var t_id = this.teacherform.value.t_id;
    var t_name = this.teacherform.value.t_name;
    var t_desig = this.teacherform.value.t_desig;
    var t_dob = this.teacherform.value.t_dob;
    var t_pswd = this.teacherform.value.t_pswd;
    var t_gender = this.teacherform.value.t_gender;
    var t_phone = this.teacherform.value.t_phone;
    var  t_quali = this.teacherform.value.t_quali;
    var  t_address= this.teacherform.value.t_address
    formData.append('file',t_p_image) ;
    formData.append('t_id',t_id) ;
    formData.append('t_name',t_name);
    formData.append('t_desig',t_desig);
    formData.append('t_dob',t_dob);
    formData.append('t_pswd',t_pswd);
    formData.append('t_email',t_email);
    formData.append('t_gender',t_gender);
    formData.append('t_phone',t_phone);
    formData.append('t_quali',t_quali);
    formData.append('t_address',t_address);



    // console.log(formData)


    //  this.MapFormValuesToTeacherModel();

    if(this.teacher._id){

    this.teacherService.updateTeacher(this.teacher._id,formData).subscribe(
      ()=>this.router.navigate(['teacher']),
      (err:any)=>console.log(err)


    );
  }else{

    this.teacherService.createTeacher(formData).subscribe(
      ()=>this.router.navigate(['teacher']),
      (err:any)=>console.log(err)

    );}
     }


  getTeacherr(techId:any){
    this.teacherService.getTeacher(techId).subscribe(
      (teacher:Teacher)=>{
        this.editTeacher(teacher);
        this.teacher = teacher
       } ,
      (err:any)=>{
        console.log(err);
      }

    )

  }



editTeacher(teacher:Teacher){
 this.teacherform.patchValue({
    t_p_img:teacher.t_p_img,
     t_id: teacher.t_id,
    t_name: teacher.t_name,
    t_desig: teacher.t_desig,
    t_dob: teacher.t_dob,
    t_pswd: teacher.t_pswd,
    t_email: teacher.t_email,
    t_gender: teacher.t_gender,
    t_phone: teacher.t_phone,
    t_quali: teacher.t_quali,
    t_address: teacher.t_address
    });
}


}

这是教师服务服务

import { Injectable } from '@angular/core';
import {Teacher} from './teacher';
import {HttpClient,HttpHeaders} from '@angular/common/http';
import {Observable,throwError, from} from 'rxjs';
import {retry,catchError} from'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TeacherServiceService {

  // Headers
  httpOptions={ 
    headers: new HttpHeaders({
      'content-type':'application/json'
    })
  }
  //Api Address
  apiUrl = 'http://localhost:3000';

  constructor(private http:HttpClient) { }
  // Requests

  createTeacher(teacher:any) {

    return this.http.post(this.apiUrl+'/teacher',teacher)
     .pipe(
       retry(2),
       catchError(this.handleError)
     )};
   //Getting All the teacher
   showTeachers(): Observable <Teacher[]> {

    return this.http.get<Teacher[]>(this.apiUrl+'/teacher',)
     .pipe(
       retry(2),
       catchError(this.handleError)
     ) 

   };
  // get a Single Teacher
  getTeacher(id:any): Observable <Teacher>{
    return this.http.get<Teacher>(this.apiUrl + '/teacher/'+id, this.httpOptions)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )};

    // Updating Teacher
    updateTeacher(id,formData:any) {
      return this.http.put(this.apiUrl + '/teacher/'+id, formData)
      .pipe(catchError(this.handleError));
      };

使用 Postman Put 请求这是放置请求工作图像

不适用于 formData Put 请求编辑/放置请求时不工作

您正在尝试使用不正确的文件设置 value 属性,它会抛出错误,

this.teacherform.get('t_p_img').setValue(file);

检查此解决方案

https://stackoverflow.com/a/59361203/7122286

好的,你可以这样做

第一的:

slectedFile: File;
//imgUrl for showing it in html tag
imgUrl = '../assets/img/profilepic.png';

第二:

form: FormGroup = this.fb.group({
   //........
   file: [null]
});

第三:

onFileSelect(file) {
    if (file.target.files[0]) {
      this.slectedFile = file.target.files[0] as File;
      const reader = new FileReader();
      reader.readAsDataURL(this.slectedFile);
      reader.onload = (event: any) => {
        this.imgUrl = event.target.result;
      };
   }
}

最后:

我认为你的主要问题在这里

  const data= new FormData();
  if (this.slectedFile) {
    data.append('file', this.slectedFile, this.slectedFile.name);
  }

我应该提到个人使用这个包作为输入

https://www.npmjs.com/package/ngx-material-file-input

在 html 方面,您只需说:

<mat-form-field class="col-md-12 ml-10 ngxmatfileinput">
    <ngx-mat-file-input
    (change)="onFileSelect($event)"
    formControlName="file"
    accept="image/*">
    </ngx-mat-file-input>
    <img [src]="imgUrl" class="float-left icon-fileupload" />
</mat-form-field>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM