Angular 4 image upload

how can i append image to object and post it which is mutipart formdata

below is service

__________

postFile(id,fileToUpload){
const headers = new HttpHeaders();
headers.append(‘Content-Type’, ‘multipart/form-data’);
  debugger;
return this._http.post(“http://********:8080/****/**/report/addReport/”+id,fileToUpload,{headers:undefined})
}
__________________

import { Component, OnInit } from ‘@angular/core’;
import { Http, Headers,Response } from ‘@angular/http’;
import { ServiceService } from ‘…/service.service’;
@Component({
selector: ‘app-reportissue’,
templateUrl: ‘./reportissue.component.html’,
styleUrls: [’./reportissue.component.css’]
})
export class ReportissueComponent implements OnInit {
report={}
// report={
// “vehicleNum”:this.report.vehicleNum,
// “offenceCategory”:this.report.offenceCategory,
// “vehicleType”:this.report.vehicleType,
// “location”:this.report.location,
// “description”:this.report.description
// }
formData={}
constructor(private http: Http,private fileUploadService: ServiceService) { }

ngOnInit() {
}

fileToUpload: File = null;
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
//this.append = this.report;

}

reportissue(report) {
debugger;

var uid = localStorage.getItem(‘userid’);
//this.report1 = this.report;
//var formData = new FormData();
var formData = new FormData();
formData.append(‘img1’, this.fileToUpload, this.fileToUpload.name);
//formData.append(‘report1’,this.report);
//formData.append(‘fileKey’, this.fileToUpload, this.fileToUpload.name);
formData.append(‘vehicleNum’,report.vehicleNum);
formData.append(‘offenceCategory’,report.offenceCategory);
formData.append(‘vehicleType’,report.vehicleType);
formData.append(‘location’,report.location);
formData.append(‘description’,report.description);

this.fileUploadService.postFile(uid,formData).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}

1 Like

Hi @sra-one,

It looks like you opened this topic in a couple different places. We do ask that Community Forum members abide by our Code of Conduct, which states that topics should not be cross-posted. For this reason, we do ask that you please restrict the conversation to a single thread. 

I will be closing this topic, and you can continue the conversation in the original topic here.

For additional guidance, please review our Community Forum Code of Conduct.

Cheers!