c# - 将文件从 Angular 发送到 .NET Core

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

我一直在尝试将 xls(或任何其他)文件从我的 Angular 应用程序发送到 .NET 核心 Controller 。我尝试了很多方法,但都没有用...

这是我的组件,点击按钮我调用我的服务:

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 {
      }
    });

服务方式如下:

 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);
}

这是我的 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;//.....
    }
}

但请求永远不会到来...我得到 POST http://localhost:44328/api/Student net::ERR_CONNECTION_RESET

在我的 startup.cs 类中,我添加了 cors,一切似乎都是正确的,我真的不明白这里出了什么问题..

启动.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();
    }

这里有什么问题?我真的没有想法,也许在花了这么多时间之后我需要对此有新的想法

最佳答案

我遇到过同样的情况,下面是我是如何实现的。

上传 View .component.html

<div fxLayout="column" fxLayoutAlign="start center" class="update-upload">
    <form id="updateFormHtml" fxLayout="row" fxLayoutAlign="center center" #updateForm="ngForm" (submit)="uploadFile()">
    <div class="file-dropzone">
      <label for="file" class="text">Click here or Drag and Drop file here</label>
      <input id="file" type="file" accept=".json" (change)="setChosenFile($event)" />
    </div>
  </form>
  <div *ngIf="chosenFileName" fxLayout="column" fxLayoutAlign="start center" class="file-info">
    <div class="file-name">{{ chosenFileName }}</div>
    <button form="updateFormHtml" mat-raised-button color="primary">Upload</button>
  </div>
</div>

我的 upload-view.component.ts 有这个类:

export class AdminViewComponent {
  chosenFileName: string;
  chosenFile: any;

  constructor(private snackbar: MatSnackBar, private uploadService: UploadService)   { }

  setChosenFile(fileInput: Event) {
    console.log(fileInput);
    const control: any = fileInput.target;
    if (!control.files || control.length === 0) {
      this.chosenFileName = null;
      this.chosenFile = null;
    } else {
      this.chosenFileName = control.files[0].name;
      this.chosenFile = control.files[0];
    }
  }

  uploadFile() {
    const uploadData = new FormData();
    uploadData.append('file', this.chosenFile, this.chosenFileName);
    console.log(uploadData);

    this.uploadService
        .uploadFile(uploadData)
        .subscribe(
          (response) => {
            this.snackbar.open('File uploaded successfully', null,
            {
              duration: 7000, verticalPosition: 'top',
              horizontalPosition: 'center'
            });
          },
          (error) => {
            this.snackbar.open(error.status, null,
              {
                duration: 7000, verticalPosition: 'top',
                horizontalPosition: 'center'
              });
          }
        );
  }
}

在upload.service.ts中有这个方法

public uploadFile(data: any) {
    const url = `${this._baseUrl}/api/script/status`;
    return this.httpClient.post<ActionResponse>(url, data, { headers: new HttpHeaders({
      'Authorization': `Bearer ${this.Token}`
      })
    });
  }

这是我的 .Net Core Controller 方法:

[HttpPost("upload")]
public IActionResult UploadFile([FromForm(Name ="file")] IFormFile resultFile)
{
    if (resultFile.Length == 0)
        return BadRequest();
    else
    {
        using (StreamReader reader = new StreamReader(resultFile.OpenReadStream()))
        {
            string content = reader.ReadToEnd();
            //Removed code
        }
    }
}

关于c# - 将文件从 Angular 发送到 .NET Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837380/

相关文章:

c# - 计算与源文件相比的wav文件中的噪声量

javascript - 使用 Angular 2 自定义库

c# - 如何在不触发 PageSizeChanged 事件的情况下以编程方式设置 RadGrid 的页面大小

c# - 在哪里放置带有 API key 的 JSON 文件以进行私有(private)访问

asp.net - 向 asp.NET RadioButton 控件添加自定义属性

asp.net - 一种#if(调试符号),但用于 web.config 文件

c# - 如何使用 Automapper 函数调用递归地将实体映射到 View 模型?

angular - 如何删除 FormArray 的所有元素但一个特定索引?

angular - (change) $event 不起作用,可能是语法问题

c# - 如果未处理 StreamWriter,MemoryStream.ToArray() 返回空数组