我想在同一个请求中实现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是关键,这里有一个如何做到这一点的例子.