如何在相同的请求中将Angular2发布JSON数据和文件 [英] How to angular2 post JSON data and files In same request

查看:125
本文介绍了如何在相同的请求中将Angular2发布JSON数据和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一请求中实现发布文件和Json数据.

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

下面是上传文件代码:

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();

如何与angular2集成 http.post(url,JSON.stringify(data)).

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

推荐答案

所以我也一直在尝试这样做,而对于看起来非常简单的事情,我却很麻烦地找到了解决方案.希望一些同事能帮助我,我们提出了一些合理的建议.

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.

该文档对我们有很大帮助: https://developer .mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

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

这是Angular代码:

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);
  }
}

@Supamiu 所述,使用Blob是关键,这是如何实现此目的的示例.

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

这篇关于如何在相同的请求中将Angular2发布JSON数据和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆