I've been trying to send xls (or any other) file from my angular application to .NET core controller. I tried so many ways and none of them worked...
this is my component where on button click I cal my service:
handleFileInput(file: FileList) {
this.fileToUpload = file.item(0);
const url = 'http://localhost:44328/api/Student';
this.studentService.postFile(this.url, this.fileToUpload)
.subscribe((res: any) => {
},
(err) => {
if (err.status === 401) {
} else {
}
});
}
here's service method:
postFile(url: string, fileToUpload: File): Observable<Response> {
const formData: FormData = new FormData();
formData.append('File', fileToUpload, fileToUpload.name);
const headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
const options = new RequestOptions({ headers });
return this.http.post(url, formData, options);
}
And here's my controller:
[Route("/api/[controller]")]
public class StudentController : Controller
{
private readonly IStudentsService _service;
public StudentController(IStudentsService service)
{
_service = service;
}
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile()
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var httpRequest = HttpContext.Request.Form;//.....
}
}
But the request never comes... I get POST http://localhost:44328/api/Student net::ERR_CONNECTION_RESET
In my startup.cs class I added cors and everything seems correct, and I really don't understand what's wrong here..
startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(x => x.AddProfile(new MappingsProfile()));
services.AddDbContext<museumContext>(options =>
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllOrigins"));
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder =>
builder.WithOrigins("http://localhost:44328")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
app.UseAuthentication();
app.UseCors("AllowAllOrigins");
app.UseMvc();
}
What is wrong here? I'm really out of ideas, maybe I need a fresh thoughts on this after spending so much time