Victoria Unizhona
Victoria Unizhona

Reputation: 266

How do I upload CSV file via REST API in Angular?

In my html I have:

 name="file" type="file"
 accept=".csv"

In ts: I get file - $event.target.files.item(0);

Then I pass it to the service

  uploadCSVFile( file) {
    const uploadedFile = new FormData();
    uploadedFile.append( 'file', file, file.name);
    const url = `MyURL`;
    return this.http.post(url, uploadedFile);
  }

The problem is that it says File must have a contentType text/csv But when I add headers -

{headers:  new HttpHeaders().append('Content-Type', 'text/csv')}

It is complaining that request is not multipart.

Upvotes: 3

Views: 13162

Answers (2)

Victoria Unizhona
Victoria Unizhona

Reputation: 266

The issue was related to MIME types mismatch. The files MIME type is not recognized as same across platforms. .csv file in OSX is recognized as text/csv, whereas in Windows it is recognized as application/vnd.ms-excel.

Here is the solution - change line:

 uploadedFile.append( 'file', new Blob([file], { type: 'text/csv' }), file.name);

Upvotes: 10

Zulqarnain Jalil
Zulqarnain Jalil

Reputation: 1691

you need to make your content type as multipart you can modify your code as given below

uploadCSVFile( file) {
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** In Angular 5, including the header Content-Type can invalidate your request */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        return this.http.post(url, formData, options)
}

another way is to use

headers.append('enctype', 'multipart/form-data');

Upvotes: 0

Related Questions