How to return an Excel file from ASP.NET Core Web API web-app?

后端 未结 4 1704
情话喂你
情话喂你 2020-12-31 09:47

In similar questions, with this code works to download a PDF:

I\'m testing with local files (.xlsx, .pdf, .zip) inside the Controller folder.

4条回答
  •  旧时难觅i
    2020-12-31 10:26

    I had this same issue. My issue was being caused by the client request, not the server response. I solved it by adding a response content type to my Get request's header options. Here is my example in Angular 2.

    Request from client (Angular 2) **requires filesaver.js library

    this._body = '';
    
        let rt: ResponseContentType = 2; // This is what I had to add ResponseContentType (2 = ArrayBuffer , Blob = 3)
            options.responseType = rt;
        if (url.substring(0, 4) !== 'http') {
            url = config.getApiUrl(url);
        }
    
        this.http.get(url, options).subscribe(
            (response: any) => {
                let mediaType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                let blob = new Blob([response._body], { type: mediaType });
                let filename = 'test.xlsx';
                fileSaver.saveAs(blob, filename);
            });
    

    Server side code. (.net core)

        [HttpGet("{dataViewId}")]
        public IActionResult GetData(string dataViewId)
        {
            var fileName = $"test.xlsx";
            var filepath = $"controllers/test/{fileName}";
            var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    
            byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
            return File(fileBytes, mimeType, fileName);
        }
    

    here are the references if you want to see.

    Corrupted download in AngularJs app

    C# File Download is Corrupt

提交回复
热议问题