Sachin Muthumala
Sachin Muthumala

Reputation: 765

How to send form data in ts file using angular?

I want to send data to back-end using form data type. I want to upload a photo and the name using html, In the back-end file uploaded successfully, bur not takes name in front-end, I have checked the back-end using postman. That is fully worked.

HTML file

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

Type Script file

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

Backend-respose

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

Upvotes: 0

Views: 3214

Answers (2)

sonaliii
sonaliii

Reputation: 56

Please make use of FormBuilder and FormGroup first and then append the data.

export class UploadFile {

 uploadForm: FormGroup;

 this.uploadForm = this.formBuilder.group({
      profile: ['']
    });
const formData = new FormData();
    formData.append('file', this.uploadForm.get('profile').value);
}

Upvotes: 2

Sam
Sam

Reputation: 1861

You are not binding the name value from the input to anything.

You could use two way data binding for this - for example.

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

Then upload like this

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

Upvotes: 3

Related Questions