![](/img/trans.png)
[英]How can I send a File via HTTP POST along with my other text parameters?
[英]How can I send FormData and an object in one http post?
因此,我试图发布一个帖子(例如Facebook上的帖子),其中包含标题,描述和图像。 我使用Angular和ASP.NET CORE来做到这一点。 我的数据库结构是我将我的图像保存在wwwroot服务器文件夹上,并希望创建一个表'帖子',其中包含指向此文件夹的链接以获取图像。
创建帖子和发送图像都有效,但现在我想在一个HttpPost中发送我的对象'Post'和我的图像(FormData)。 但它似乎不起作用。
ANGULAR
onSubmit(Image) {
let post = new Post(this.post.value.titel, this.post.value.omschrijving, new Date(), this._userService.user$.getValue())
this._postService.voegPostToe(post, this.selectedFile).subscribe();
this.post.reset();
}
voegPostToe(post: Post, fileToUpload: File) {
const formData: FormData = new FormData();
formData.append('Image', fileToUpload, fileToUpload.name);
return this.http.post(`${environment.apiUrl}/posts`, (post.toJson(), formData));
}
ASP.NET
[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> PostPost(Post post)
{
var file = HttpContext.Request.Form.Files["Image"];
string fileName = new String(Path.GetFileNameWithoutExtension(file.FileName).Take(10).ToArray()).Replace(" ", "-");
fileName = fileName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(file.FileName);
string filePath = _env.WebRootPath + "\\Images\\" + fileName;
using (var fileSrteam = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileSrteam);
}
post.Fotolink = filePath;
_postRepository.Add(post);
_postRepository.SaveChanges();
return NoContent();
}
如果我尝试只发送FormData,我的图像上传,如果我只尝试发送我的帖子对象,它也有效。 然而,这两个一起给出了一个错误,即我的帖子的必填字段没有填写,这让我相信我的“帖子对象”不会发送。 但是我似乎没有发现我的错误。
编辑 :如果需要,我可以提供额外的代码。
您必须使用FormData发送所有数据,因此您的代码将是这样的。 您还必须对post对象进行字符串化,这样您只需要提交FormData
let post = new Post(this.post.value.titel, this.post.value.omschrijving, new Date(), this._userService.user$.getValue())
const formData: FormData = new FormData();
formData.append('Image', fileToUpload, fileToUpload.name);
formData.append('ObjectData', JSON.stringify(post));
return this.http.post(`${environment.apiUrl}/posts`, formData);
然后在服务器中你的动作应该接受这样的参数中的[FromForm]
public async Task<IActionResult> PostPost([FromForm]Post post)
然后你需要解析我刚提交的ObjectData中的json数据
var resource = JObject.Parse(post.ObjectData);
请根据您的代码进行相应调整
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.