[英]Can not send a file with Ajax using FormData in angular 7
我使用ASP.NET Core作为后端,并且尝试使用angular 7中的ajax发送文件。我创建了FormData类的对象,并使用append方法将文件添加到了该对象。 但是尝试在api上方发布时会出现错误:
Error: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":415,"statusText":"Unsupported Media Type","url":"https://localhost:44319/Api/TimeLinePost","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://localhost:44319/Api/TimeLinePost: 415 Unsupported Media Type","error":{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"0HLLKF4AT3QD7:00000005"}}
这是我的角度代码:
export class StatusComponent {
selectedImage: File = null;
constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
}
onImageSelected(event) {
this.selectedImage = <File>event.target.files[0];
}
update() {
const fd = new FormData();
fd.append('image', this.selectedImage, this.selectedImage.name);
this.http.post<boolean>(this.baseUrl + 'Api/TimeLinePost', fd).subscribe(
result => {
},
error => {
alert('Ops! Somthing went wrong!');
console.log(`Error: ${JSON.stringify(error)}`)
}
)
}
}
这是我的api:
[HttpPost]
public bool Post(IFormFile image)
{
return true;
}
它可以通过两种方式解决。
1)将[FromForm]
属性添加到操作参数(如在此问题中回答 ):
[HttpPost]
public bool Post([FromForm] IFormFile image)
{
return true;
}
2)在配置中添加SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
。 它将自动解决绑定问题:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.