How to angular2 post JSON data and files In same request

后端 未结 4 2223
谎友^
谎友^ 2020-12-06 01:16

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<{compl         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 01:55

    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.

提交回复
热议问题