Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

angular - 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)).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...