file-upload – 如何在同一请求中发布角色2发布JSON数据和文件

前端之家收集整理的这篇文章主要介绍了file-upload – 如何在同一请求中发布角色2发布JSON数据和文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在同一个请求中实现post文件和Json数据.

以下是上传文件代码

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))集成.

解决方法

所以我一直在尝试这样做,对于看起来非常简单的东西,我最终找到了解决方案的麻烦.希望有些同事帮助我,我们想出了一些合理的东西.

这个文档帮助了我们很多:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

这是Angular代码

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是关键,这里有一个如何做到这一点的例子.

原文链接:https://www.f2er.com/js/158999.html

猜你在找的JavaScript相关文章