代码之家  ›  专栏  ›  技术社区  ›  Krishnan

如何在Visual Studio 2017中将excel文件从angular 4传递到C#controller?

  •  1
  • Krishnan  · 技术社区  · 7 年前

    在我的web应用程序中,我必须导入一个excel文件,并希望将其传递给服务器端控制器。

    在服务器端,我使用了EPPlus。

    我怎样才能达到同样的效果?

    请任何人帮助实现同样的目标

    2 回复  |  直到 7 年前
        1
  •  1
  •   alsami    7 年前

    在模板中创建文件输入

    <input type="file" #fileInput />
    <button (click)="uploadFile();">Upload</button>
    

    然后前往您的组件

    @ViewChild('fileInput') fileInput;
    // inject httpclient from @angular/common/http
    ...
    public uploadFile(): void {
       if (this.fileInput.files.length === 0) {
          return; // maybe needs more checking
       }
    
       const formData = new FormData();
       formData.append('file', this.fileInput.files[0]);
       this.http.post('http://my-url/api/my-endpoint', formData).subscibre(...); // the usual
    }
    

    现在在API中创建这样的端点

    [HttpPost]
    // the name here must be file for the parameter, bc you declared it as such in your formdata
    public IActionResult UploadFile([FromBody] IFormFile file)
    {
        // depending on what you wanna do you can either create and store it in the filesystem or copy the file into a byte array and store it in your db
    }
    

    如果您明确了要保存文件的位置,我可以展开C代码。但一般来说,这是您从前端接收文件的方式,也就是从后端接收文件的方式。

        2
  •  1
  •   Krenom    7 年前

    上传文件或使用第三方预制组件时有很多类似的问题。。。

    还有很多关于服务器端接收文件的类似问题和示例。。。