0

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

2 Answers 2

3

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)
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.