Angular 使用.NET Core进行角度多部分上载,文件在后端变为空
我正试图将一个简单的文件上载到我的后端dotnet核心应用程序,但该文件显示为Angular 使用.NET Core进行角度多部分上载,文件在后端变为空,angular,typescript,.net-core,Angular,Typescript,.net Core,我正试图将一个简单的文件上载到我的后端dotnet核心应用程序,但该文件显示为null,但description不为null .NET核心控制器: [AllowAnonymous] [HttpPost] [Route("upload")] public async Task<IActionResult> ImageUpload(IFormFile file, [FromQuery] string description) { if (file == null) {
null
,但description
不为null
.NET核心控制器:
[AllowAnonymous]
[HttpPost]
[Route("upload")]
public async Task<IActionResult> ImageUpload(IFormFile file, [FromQuery] string description)
{
if (file == null)
{
return BadRequest("Failed to upload file");
}
// File is alway null!
return Ok("Good!");
}
您需要将数据作为FormData()从角度发布,您还可以使用.append()将描述设置为服务方法中的fd对象。您将使用Request=>Request.Form在API中获取所有附加数据 API
[HttpPost("SaveProfilePic")]
public ResponseResult SaveProfilePic(IFormFile files)
{
var file = Request.Form.Files[0];
var form = Request.Form;
}
棱角分明
<form (ngSubmit)="Save(f)" #f="ngForm">
<input type="file" name="profile_pic" (change)="setProfilePic($event)">
<input type="submit" value="submit" />
</form>
Save(form)
{
this.MyService.SaveProfilePic(this.profile_pic, 'description').subscribe(res => {
})
}
setProfilePic(event:any)
{
if (event.target.files && event.target.files[0]) {
this.profile_pic = event.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event:any) => { // called once readAsDataURL is completed
}
}
}
<form (ngSubmit)="Save(f)" #f="ngForm">
<input type="file" name="profile_pic" (change)="setProfilePic($event)">
<input type="submit" value="submit" />
</form>
Save(form)
{
this.MyService.SaveProfilePic(this.profile_pic, 'description').subscribe(res => {
})
}
setProfilePic(event:any)
{
if (event.target.files && event.target.files[0]) {
this.profile_pic = event.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event:any) => { // called once readAsDataURL is completed
}
}
}
public SaveProfilePic(picture: File,fileName): any {
const fd = new FormData();
fd.append('image', picture, fileName);
return this._http.post(this.url + 'MyController/SaveProfilePic', fd);
}