繁体   English   中英

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

[英]Upload images/files from Angular 7 to .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.

将此添加到您的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'});
    }

在Startup.cs上添加ConfigureServices:

services.AddCors();

在配置上添加

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM