3

Why do im receving the Cors Error

Access to XMLHttpRequest at 'http://localhost:5000/api/upload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As far as i understand. The cors is enabled in my startup class in my asp.net core web api

And here is my code

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(x => x.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseAuthentication();
        app.UseMvc();
}

And this is my Angular 7 Code

The html for fileupload

<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
  <div class="form-group">
      <input type="file" name="image"  />
  </div>
  <div class="form-group">
      <button class="btn btn-primary">Submit</button>
  </div>
</form>

And this is the fileupload.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-fileupload',
  templateUrl: './fileupload.component.html',
  styleUrls: ['./fileupload.component.css']
})
export class FileuploadComponent implements OnInit {
  fileData: File = null;
  formGroup = new FormGroup({
    one: new FormControl
  });
  constructor(private http: HttpClient) { }

  fileProgress(fileInput: any) {
    this.fileData = <File>fileInput.target.files[0];
  }

  ngOnInit() {
  }

  onSubmit() {
    const formData = new FormData();
    formData.append('file', this.fileData);
    this.http.post('http://localhost:5000/api/upload', formData)
    .subscribe(res => {
      console.log(res);
      alert('SUCCESS !!');
    })

    console.log('Called');
  }

}

Actually im following this tutorial:

https://www.tutsmake.com/new-angular-7-upload-file-image-example/

And im in the part where i am checking the file upload api with the help of the Angular 7. I tested the API using postman and it worked correctly with the code in the api so far

enter image description here

And below is the Upload controller code

[Produces("application/json")]
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {

            try
            {
                var file = Request.Form.Files[0];
                Console.WriteLine();

                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }
    }

I'm also receving an error

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.' on

var file = Request.Form.Files[0]; 

is this because of the Angular 7 is not sending data?

Thank you so much.

Zze
  • 18,229
  • 13
  • 85
  • 118
mecocopy
  • 187
  • 1
  • 3
  • 14
  • Would you like to upload a file? If so, it should be a post and not a get. Usually you should check if there are any files uploaded, but also you should handle if there is more than one file in the list. There is a simple example in the mircosoft docs: https://learn.microsoft.com/de-de/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2 – Pierre Apr 01 '19 at 07:01
  • For information about using cors in ASP.NET Core: https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core – Pierre Apr 01 '19 at 07:10

1 Answers1

3

Access to XMLHttpRequest at 'http://localhost:5000/api/upload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Actually, I doubt whether you forgot to restart the ASP.NET Core Server after you configure the CORS.

Assuming you're using the default template, your existing code works fine for me. If you still cannot make it, you could paste the complete code of your Startup class.

I'm also receving an error

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.' on

var file = Request.Form.Files[0]; 

is this because of the Angular 7 is not sending data?

Yes. That's because you haven't binded an event handler to set the fileData property when selecting a file.

To fix it, create a method of onFileChange(event):

@Component({
  selector: 'app-fileupload',
  templateUrl: './fileupload.component.html',
  styleUrls: ['./fileupload.component.css']
})
export class FileuploadComponent implements OnInit {

  // ...

  onFileChange(event){
    this.fileData = <File> event.target.files[0];
  }

  // ...
}

and change your template as below:

<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
  <div class="form-group">
      <input type="file" name="image" (change)="onFileChange($event)"  />
  </div>
  <div class="form-group">
      <button class="btn btn-primary">Submit</button>
  </div>
</form>

As a side note, don't return a null as an IActionResult within your action method. It will result in an unhandled exception:

    public IActionResult Index()
    {
        try
        {
            var file = Request.Form.Files[0];
            Console.WriteLine();

            return null;             ////////// don't return null
        }
        catch (Exception ex)
        {
            // ...
        }
    }
itminus
  • 23,772
  • 2
  • 53
  • 88