Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you POST a FormData object in Angular 2?

I need to upload a file and send some json along with it, I have this function:

POST_formData(url, data) {         var headers = new Headers(), authtoken = localStorage.getItem('authtoken');          if (authtoken) {             headers.append("Authorization", 'Token ' + authtoken)         }          headers.append("Accept", 'application/json');         headers.delete("Content-Type");          var requestoptions = new RequestOptions({             method: RequestMethod.Post,             url: this.apiURL + url,             headers: headers,             body: data         })          return this.http.request(new Request(requestoptions))          .map((res: Response) => {             if (res) {                 return { status: res.status, json: res.json() }             }         })     } 

My issue is, if I set the content-type to "multipart/form-data" my server complains about the boundaries, if I remove the content-type header completely, my server complains that it "text/plain" a supported media type.

So, how do you send FormData with angular2?

like image 507
Sebastian Olsen Avatar asked May 11 '16 23:05

Sebastian Olsen


People also ask

How do I post using form data?

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.

Can we send object in FormData?

Yes you can, you can append to formData objects.

What is FormData in angular?

The FormData. getAll() method provides an array of all the values associated with a specific key. The FormData.has() methods provides a boolean indicating whether a FormData instance contains a specific key. The FormData. keys() method provides an iterator for going through all the keys contained in the form instance.


2 Answers

Template:

<label class="btn btn-primary">   <input type="file" style="display: none;" multiple="true" (change)="fileChange($event)" accept=".xml">   <span>Click Me!</span> </label> 

UPD: Angular 5 - HttpClient + Typescript

onFileUpload(event: EventTarget) {    const eventObj: MSInputMethodContext = <MSInputMethodContext>event;   const target: HTMLInputElement = <HTMLInputElement>eventObj.target;   const files: FileList = target.files;    const formData: FormData = new FormData();    for (let i = 0; i < files.length; i++) {     formData.append('file', files[i]);   }    // POST   this.httpClient.post<AnalyzedData>(uploadUrl, formData).subscribe(...); } 

old Http lib - before Angular 4.3:

fileChange(event) {     let files = event.target.files;         if (files.length > 0) {         let formData: FormData = new FormData();         for (let file of files) {              formData.append('files', file, file.name);         }         let headers = new Headers();         headers.set('Accept', 'application/json');         let options = new RequestOptions({ headers: headers });         this.http.post(uploadURL, formData, options)             .map(res => res.json())             .catch(error => Observable.throw(error))             .subscribe(             data => {                 // Consume Files                 // ..                 console.log('uploaded and processed files');             },             error => console.log(error),             () => {                 this.sleep(1000).then(() =>                     // .. Post Upload Delayed Action                 )             });     } } 
like image 86
Dhruvan Ganesh Avatar answered Sep 29 '22 10:09

Dhruvan Ganesh


It's an Open Isuue on Angular2 Git Repository, and there is also a Pull Request waiting to be merged, hope that it will be merged soon.


Alternatively,

You can use XMLHttpRequest Object directly, for that.

And don't forget to set the header

xhr.setRequestHeader("enctype", "multipart/form-data");  // IE workaround for Cache issues xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("Cache-Control", "no-store"); xhr.setRequestHeader("Pragma", "no-cache"); 

on the XMLHttpRequest that you make.


Similar Questions:

How to upload file in Angular2

Angular 2 File upload from input type=file

Angular2 post uploaded file

like image 36
Ankit Singh Avatar answered Sep 29 '22 09:09

Ankit Singh