0

I was trying to upload files on server using angular reactive form.When i try to edit form that generate an error internal server error but when i use postman it updates file successfully i don`t know what i am missing in my FormData put request? post request works successfully

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


}

This is TeacherServiceService

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

working with Postman Put request This is Put Request Working image

Not working with formData Put request Not Working when edit/put request

6
  • can u share the curl command of postman & the screenshot of the error that you are getting Commented Dec 28, 2019 at 6:44
  • @ShashankVivek i did attached please check Commented Dec 28, 2019 at 8:05
  • @SAADA82 Try to open chrome network tab and check the outgoing PUT request to see the request body to know what happens Commented Dec 28, 2019 at 8:51
  • i did check i am unable to understand whats wrong Commented Dec 28, 2019 at 9:02
  • @SAADA82 : There seems to be something which is not detectable from the provided code. With 500 error code, your response is getting to server and the server is throwing error. Can you check the form Data on server side once and see of all values are passed correctly from client side Commented Dec 28, 2019 at 10:18

2 Answers 2

2

You are trying to set value property with file which is not correct and It'll throw error ,

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

Check this solution

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

Sign up to request clarification or add additional context in comments.

2 Comments

i did check your solution. problem is different here when i create new user with file also works fine but when i edit user that throws error
please check now i did
1

ok you can do it like this

First:

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

Second:

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

Third:

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

And Last:

which I assume your main problem is here

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

and I should mention that personally use this package for input

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

and in the html side you just say :

<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>

9 Comments

Thanks for explanation. When i register first time it works fine but when i edit it does not work ?
what do you mean by edit? reselect the image you mean?
Edit Complete form, i mean put request
please have a look i have update question with screen shots
change the content type to 'Content-Type': multipart/form-data and try again OR 'Content-Type': undefined or delete it completely
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.