首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将文件从angular发送到.NET内核

将文件从angular发送到.NET内核
EN

Stack Overflow用户
提问于 2019-02-23 09:37:09
回答 2查看 1.5K关注 0票数 5

我一直在尝试将xls (或任何其他)文件从我的angular应用程序发送到.NET核心控制器。我试了那么多方法都没成功...

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

代码语言:javascript
运行
复制
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 {
      }
    });

}

以下是服务方法:

代码语言:javascript
运行
复制
 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);
}

这是我的控制器:

代码语言:javascript
运行
复制
 [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:

代码语言:javascript
运行
复制
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();
    }

这里出了什么问题?我真的无计可施了,也许在花了这么多时间之后,我需要一个新的想法

EN

Stack Overflow用户

发布于 2019-02-23 11:40:32

我也经历过同样的情况,下面是我是如何实现的。

upload-view.component.html

代码语言:javascript
运行
复制
<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有这样的类:

代码语言:javascript
运行
复制
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中有这样的方法

代码语言:javascript
运行
复制
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核心控制器方法:

代码语言:javascript
运行
复制
[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
        }
    }
}
票数 3
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54837380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档