如何 angular2 在同一个请求中发布 JSON 数据和文件 [英] How to angular2 post JSON data and files In same request
问题描述
我想在同一个请求中实现post文件和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/en-US/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屋!