将文件从 angular 发送到 .NET Core

use*_*222 5 c# asp.net typescript asp.net-core angular

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

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

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 {
      }
    });
Run Code Online (Sandbox Code Playgroud)

}

这是服务方法:

 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);
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

 [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;//.....
    }
}
Run Code Online (Sandbox Code Playgroud)

但请求永远不会到来......我明白了 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();
    }
Run Code Online (Sandbox Code Playgroud)

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

Ram*_*ran 3

我也经历过同样的场景,以下是我实现这一目标的方法。

\n\n

upload-view.component.html

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

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

\n\n
export class AdminViewComponent {\n  chosenFileName: string;\n  chosenFile: any;\n\n  constructor(private snackbar: MatSnackBar, private uploadService: UploadService)   { }\n\n  setChosenFile(fileInput: Event) {\n    console.log(fileInput);\n    const control: any = fileInput.target;\n    if (!control.files || control.length === 0) {\n      this.chosenFileName = null;\n      this.chosenFile = null;\n    } else {\n      this.chosenFileName = control.files[0].name;\n      this.chosenFile = control.files[0];\n    }\n  }\n\n  uploadFile() {\n    const uploadData = new FormData();\n    uploadData.append(\'file\', this.chosenFile, this.chosenFileName);\n    console.log(uploadData);\n\n    this.uploadService\n        .uploadFile(uploadData)\n        .subscribe(\n          (response) => {\n            this.snackbar.open(\'File uploaded successfully\', null,\n            {\n              duration: 7000, verticalPosition: \'top\',\n              horizontalPosition: \'center\'\n            });\n          },\n          (error) => {\n            this.snackbar.open(error.status, null,\n              {\n                duration: 7000, verticalPosition: \'top\',\n                horizontalPosition: \'center\'\n              });\n          }\n        );\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 upload.service.ts 有这个方法

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

这是我的 .Net Core 控制器方法:

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