【问题标题】:how to pass excel file to C# controller from angular 4 in Visual Studio 2017?如何将 excel 文件从 Visual Studio 2017 中的 Angular 4 传递到 C# 控制器?
【发布时间】:2018-03-13 16:23:57
【问题描述】:

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

在服务器端我使用了 EPPlus。

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

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

【问题讨论】:

    标签: excel angular typescript visual-studio-2017 epplus


    【解决方案1】:

    在模板中创建文件输入

    <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】:

      关于上传文件或使用第三方预制组件的许多类似问题...

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

      【讨论】:

        猜你喜欢
        • 2013-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多