Upload file using Angular and ASP WEB API CORE?

I have CORS policy which fine work with all request (with content-type:application/json). But when I try to upload file and using content-type:multipart/form-data I have error:

XMLHttpRequest cannot load http://localhost:20377/api/posts. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.

I don't understand why this does not work with multipart/form-data but work with application/json. Here's code: Policy setup in Startup.cs

 services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

Angular method:

public createPost(title: string, body: string, file:File) {
    const token = this.authService.getToken();
    let formData: FormData = new FormData();
   
    formData.append('File', file, file.name);
    formData.append('Title', title);
    formData.append('Body', body);
    console.log(formData);
    return this.http.post('http://localhost:20377/api/posts', formData,
        {headers: new Headers({'Content-Type': 'multipart/form-data'})})
        .map(res => {
            console.log(res);
        });

web api core controller:

    [EnableCors("CorsPolicy")]
    [HttpPost]
    public IActionResult CreatePost([FromBody] PostCreate model)
    {
        return Ok(model.Body);
    }

Upvotes: 1

Views: 688

Answers (1)

Solved

My mistake was in the place where I am passing FormBody data in Controller Action and not pass any headers on my Angular request. need to need to change on:

    [HttpPost]
    public IActionResult CreatePost([FromForm] PostCreate model)
    {
        return Ok(model);
    }

And in angular

    return this.http.post('http://localhost:20377/api/posts', formData)
        .map(res => {
            console.log(res);

Upvotes: 1

Related Questions