我知道已经有一个similar question,但它不能解决上述错误。
这是我在API控制器中的PUT操作,在Swagger
中正常运行:
[HttpPut("{id}/upload")]
public async Task<IActionResult> UploadFile(string id, IFormFile file)
{
// codes using id above are omitted, nothing to do with the error
var path = Path.Combine(
Directory.GetCurrentDirectory(),
"wwwroot",
file.FileName
);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok();
}
这是我的Angular网页中的代码:
HTML
<input type="file" (change)="setFile($event.target.files)"/>
<button (click)="save()"> Save </button>
TypeScript
forUpload: File = null;
@Input() someModel: SomeModel;
// setting of file
setFile(myFile: File){
if (myFile === null){
return;
}
this.forUpload = myFile[0];
}
// saving
save() {
const addFileFnc = this.theService.addFile.bind(this.theService);
addFileFnc(this.someModel, this.forUpload).subscribe(
() => { this.ref.close(); },
(e) => { console.log(e); }
);
}
而且,我的service是:
addFile(someModel: SomeModel, myFile: File): Observable<any> {
return this.http.put(`${api_url}/api/somemodels/${someModel.id}/upload`, {
id: someModel.id,
file: myFile
});
}
[我也使用FormData
尝试了上述问题的答案,我将forUpload
文件附加到FormData
,但不幸的是,同样的错误。如果媒体类型中没有任何设置,如何解决?
这是我如何在ASP.Net Core和Angular中上传文件
在斜角,您将需要使用FormData提交
const formdata = new FormData();
formdata.append("SomeProp ", "somestring");
formdata.append("Image ", myFile); // change your code accordingly here
return this.http.put(`${api_url}/api/somemodels/${someModel.id}/upload`, {
formdata
});
在服务器端
public class PostViewModel
{
public string SomeProp { get; set; }
public IFormFile Image { get; set; }
}
并且在我的控制器中,我使用FromForm
属性
public async Task<IActionResult> SavePost([FromForm]PostViewModel viewModel)
更新:确保像这样在ASP.Net Core中启用CORS支持
启用CORS
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(
options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
);
app.UseMvc();
}