Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to angular2 post JSON data and files In same request

I want to implement post file and Json data in the same request .

below is the upload file code :

upload(url:string,file:File):Observable<{complate:number,progress?:number,data?:Object}>{


    return Observable.create(observer => {
      const formData:FormData = new FormData(),
        xhr:XMLHttpRequest = new XMLHttpRequest();
      formData.append('uploadfile', file);


      formData.append("_csrf", this.tokenService.getCsrf());
      xhr.open('POST',url, true);
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            observer.next({complate:1,progress:100,data:JSON.parse(xhr.response)});
            observer.complete();
          } else {
            observer.error(xhr.response);
          }
        }
      };

      xhr.upload.onprogress = (event) => {
        observer.next({complate:0,progress:Math.round(event.loaded / event.total * 100)});
      };


      const headers=new Headers();
      let token: string = localStorage.getItem('access-token');
      xhr.setRequestHeader('Authorization', `Bearer ${token}`);
      xhr.send(formData);
    }).share();

How to integration with angular2 http.post(url, JSON.stringify(data)).

like image 758
Kery Hu Avatar asked Sep 26 '16 02:09

Kery Hu


People also ask

Can you include JSON in a GET request?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).


1 Answers

So I've been trying to do that too, and for something which look really simple I ended up with a lot of trouble to figure out a solution. Hopefully some coworkers helped me and we came up with something reasonable.

This documentation helped us a lot: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

And here's the Angular code:

class SomeService {
  someMethod(fileToUpload: File, name: string, version: string) {
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);

    const overrides = {
      name,
      version,
    };

    const blobOverrides = new Blob([JSON.stringify(overrides)], {
      type: 'application/json',
    });

    formData.append('overrides', blobOverrides);

    const req = new HttpRequest('POST', `some-url`, formData);

    return this.http.request(req);
  }
}

As @Supamiu said, using Blob was the key, and here's an example how to do that.

like image 93
maxime1992 Avatar answered Oct 22 '22 09:10

maxime1992