将图片/文件从Angular 7上传到.net core

时间:2019-04-04 09:39:29

标签: c# asp.net angular asp.net-core .net-core

我一直在努力从我的angular 7应用程序将图像(然后是excel文件)上传到后端服务器。我尝试了很多选择,但似乎没什么用,我不知道我在这里缺少什么。

我最后尝试过的是来自此示例(https://code-maze.com/upload-files-dot-net-core-angular/):

这是startup.cs:

 // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoMapper(x => x.AddProfile(new MappingsProfile()));
        //uzregistruojam konteksto klase
        services.AddDbContext<museumContext>(options =>
        options.UseSqlServer(_configuration.GetConnectionString("MuseumDatabase")));

        // configure strongly typed settings objects
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });
        services.AddScoped<IUsersRepository, UsersRepository>();
        services.AddScoped<IUsersService, UsersService>();

        services.AddScoped<IClassesRepository, ClassesRepository>();
        services.AddScoped<IClassesService, ClassesService>();

        services.AddCors();
        services.AddMvc();


        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors(builder =>
            builder.WithOrigins("http://localhost:4200")
       .AllowAnyHeader()
       .AllowAnyMethod()
       .AllowCredentials());
        app.UseAuthentication();

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Resources")),
            RequestPath = new PathString("/Resources")
        });
        app.UseMvc();
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
        });
    }

控制器:

   [Authorize]
[Route("api/[controller]")]
public class ChronicleController : Controller
{
    private readonly IChroniclesService _service;
    private IHostingEnvironment _hostingEnvironment;

    public ChronicleController(IChroniclesService service, IHostingEnvironment hostingEnvironment)
    {
        _service = service;
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpPost, DisableRequestSizeLimit]
    [AllowAnonymous]
    public IActionResult Upload()
    {
        try
        {
            var file = Request.Form.Files[0];
            var folderName = Path.Combine("Resources", "Images");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

            if (file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                var fullPath = Path.Combine(pathToSave, fileName);
                var dbPath = Path.Combine(folderName, fileName);

                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                return Ok(new { dbPath });
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, "Internal server error");
        }
    }

前端:

public uploadFile = (files) => {
if (files.length === 0) {
  return;
}

const fileToUpload =  files[0] as File;
const formData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);

this.httpClient.post('https://localhost:44328/api/chronicle', formData, {reportProgress: true, observe: 'events'})
  .subscribe(event => {
    if (event.type === HttpEventType.UploadProgress) {
      this.progress = Math.round(100 * event.loaded / event.total);
    } else if (event.type === HttpEventType.Response) {
      this.message = 'Upload success.';
      this.uploadFinished.emit(event.body);
    }
  });

}

我也尝试过: 前端:

public uploadFile(data: any, url: string): Observable<any> {
    return this.httpClient.post<any>(this.url + 'chronicle', data);
}

后端:

 [HttpPost, DisableRequestSizeLimit]
    [AllowAnonymous]
    public ActionResult UploadFile([FromForm(Name = "file")] IFormFile file)
    {
        if (file.Length == 0)
            return BadRequest();
        else
        {
        }

        return Ok();
    }

问题是,我认为如果删除constructor with service(然后调用存储库),它将起作用,但这不是一个选择。我在这里做什么错? 我得到的只是500个错误和Access to XMLHttpRequest at 'https://localhost:44328/api/chronicle' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

2 个答案:

答案 0 :(得分:1)

将此内容添加到您的startup.cs中,然后检查

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

在startup.cs中配置

app.UseCors("AllowAll");

为您服务

upload(formData) {
        return this.http.request('https://localhost:44328/api/chronicle', formData, {reportProgress: true, observe: 'events'});
    }

答案 1 :(得分:0)

在Startup.cs上添加ConfigureServices:

services.AddCors();

在“配置”上添加

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