1
var fd = new FormData();
fd.append('file', data.target.files[0]);
return this.http.post(url), fd).map().catch();

Using AngularJS it's working but for angular 4 when i used the same way it's not working.I am getting disk error while uploading excel file.Please help me.

Hiren Gohel
  • 4,942
  • 6
  • 29
  • 48

2 Answers2

1

Here is an example, which i use to upload files to API via FormData.

In your service file like upload.service.ts you need to create function to upload files via POST method. Here is an example for this function:

getUploadHeaders() {
    let headers = new Headers({'Accept': 'application/json'});
    headers.delete('Content-Type');
    return headers;
}    

addNewPost(newPost: FormData): Observable<FormData> {
    const endpoint = 'https://yourApiUrl.com'; 
    return this.http
        .post(endpoint, newPost, { headers: this.getUploadHeaders() })
        .catch((e) => this.handleError(e));
}

And now you should create upload function in your component, for example upload.component.ts. Here is an example for upload function with FormData.

fileToUpload: File = null;

constructor(private uploadService: UploadService) { }

handleFileInput(files: FileList) {
  this.fileToUpload = files.item(0);
}


saveFileToApi() {
  const saveForm: FormData = new FormData();      
  if (this.fileToUpload) {
    saveForm.append('fileFieldNameOnYourApi', this.fileToUpload, this.fileToUpload.name);
  }

  this.uploadService.addNewPost(saveForm).subscribe(() => {
    console.log('Upload success!');
  }, error => {
    console.log('Upload failed!');
  });
}

For uploading an file via FormData you need 3 parameters: propertyName on API endpoint, file and name of this file. And in your upload.component.html you need to have form like this one:

<form (ngSubmit)="onSubmit()">     
    <label for="fileField">Chose file to upload</label>
    <input type="file"
           id="fileField"
           name="fileField"
           (change)="handleFileInput($event.target.files)">
    <button type="submit">Speichern</button>
</form>

For more detail of FormData read this and for more information about FormData.append() read this.

Gregor Doroschenko
  • 11,488
  • 5
  • 25
  • 37
  • Thank You Gregor Doroschenko. Your answer helped to understand but if try this method I am getting 'Access-Control-Allow-Origin' header is present on the requested resource. this error and disk error so I achieved by recreating authorization and content-type. – lakshmi mullapudi Aug 17 '17 at 15:41
0

In service

public importMassUpdateExcel(file: FormData, id): Observable<any> { const headers = new Headers({ 'Authorization': '',//authorization token 'Content-Type': 'application/json; charset=UTF-8'// }); const options = new RequestOptions({ headers: headers }); return this.http .post(url, file, options) .map() .catch(); }