【问题标题】:Send file from angular to .NET Core将文件从 Angular 发送到 .NET Core
【发布时间】:2019-02-23 01:37:09
【问题描述】:

我一直在尝试将 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 {
      }
    });

}

服务方法如下:

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

这是我的控制器:

 [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,一切似乎都是正确的,我真的不明白这里出了什么问题..

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

这里有什么问题?我真的没有想法,也许在花了这么多时间后我需要重新思考一下

【问题讨论】:

  • 我建议尝试一个实用程序,独立于您现在/已经测试过的内容。在测试两个未知数之前尝试使用 postman 之类的方法,看看您的服务是否真的有效...... :)

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


【解决方案1】:

我经历过同样的场景,这就是我实现它的方法。

上传-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 控制器方法:

[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
        }
    }
}

【讨论】:

    【解决方案2】:

    在您的服务中使用此代码,附加后:

    const formData: FormData = new FormData();
    formData.append('File', fileToUpload, fileToUpload.name);
    
    const uploadReq = new HttpRequest('POST', `url`, formData, {
      reportProgress: true,
    });
    
    this.http.request(uploadReq)
    

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 2023-03-02
      • 2021-03-24
      • 2022-01-19
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      相关资源
      最近更新 更多