[英]How to send an object and files in same post request using angular front and .net core API?
I will try to go straight to the issue I am having.我将尝试直接解决我遇到的问题。 I am using Angular 8 and .net core 2.2.
我正在使用 Angular 8 和 .net core 2.2。
Lets say I have an http service to save an object that looks something like this:假设我有一个 http 服务来保存一个看起来像这样的对象:
let body = new DataObject(); //object with lost of primitive data.
body.someNumbers = 111;
body.someStrings = 'some string';
let options = { withCredentials: true };
return this.http.post<DataObject>(url, body, options).pipe(
catchError(this.handleError<DataObject>('SAVE', body))
);
My end point looks like this:我的终点是这样的:
[HttpPost]
[Route("savedata")]
public async Task<IActionResult> SaveData(DataObject data) {
await Task.Factory.StartNew((Action)(() => {
//Do stuff....
}));
return Ok();
}
So far this works fine.到目前为止,这工作正常。
I also have another service to save files that looks like this:我还有另一个服务来保存看起来像这样的文件:
let imageData = new FormData();
imageData.append('files', imgFile, imgFile.name);
let options = { withCredentials: true };
return this.http.post<FormData>(url, imageData, options).pipe(
catchError(this.handleError<FormData>('SAVE', imageData))
);
And the end point:以及终点:
[HttpPost]
[Route("saveimg")]
public async Task<IActionResult> UploadImageAsync(IFormFile imgfile) {
//converts to byte[], saves on database and returns id.
return Ok(imgId);
}
Basically I want to combine the DataObject and file on the same POST.基本上我想在同一个 POST 上组合 DataObject 和文件。 I tried doing this:
我尝试这样做:
class DataObject() { someNumbers: number; someStrings:string; imgFile: FormData;}
with a corresponding public IFormFile imgFile { get; set; }
带有相应的
public IFormFile imgFile { get; set; }
public IFormFile imgFile { get; set; }
public IFormFile imgFile { get; set; }
property on my .net class to match. public IFormFile imgFile { get; set; }
在我的.NET类属性相匹配。
But I get a 400 Bad Request Error但是我收到 400 Bad Request 错误
How do I send both, the object and image on same request to the same endpoint.如何将同一请求中的对象和图像同时发送到同一端点。 I if the question has already been answered please provide link.
如果问题已经得到回答,请提供链接。 I looked all over but not sure what is the proper search term.
我四处看了看,但不确定什么是正确的搜索词。 Thank you.
谢谢你。
You can do as follows您可以执行以下操作
this.formData = new FormData(); this.formData.append('dataFile', this.file, this.file.name);
And your json request as follows你的json请求如下
const data = { req: //your request object}
And finally append data as a blob to formData and send it to service最后将数据作为 blob 附加到 formData 并将其发送给服务
this.formData.append('jsonReq', new Blob([JSON.stringify(data)], {
type: 'application/json'
}));
return this.http.post(tgtUrl, data, httpOptionsForUpload).pipe(map((res: Response) => { //handle reponse }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.