Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 unable to download file with c# .net core api

I have an angular application where one of the grids has column with hyperlink to a csv file. This csv is on a network drive.

When user click the link, they should be able to save file to their machine (assuming all users have access).

I am using file-saver to download/save the file.

This is my c# core api controller. For testing, I have hard coded file name c:\temp\test.csv. In real application, Angular will call the api with desired file (including full path).

[HttpGet("DownLoadFile/{fileName}")]
public HttpResponseMessage DownLoadFile( string fileName)
        {
            try
            {
                fileName = @"c:\temp\test.csv"; //Hard Coding for testing only. 

                if (!string.IsNullOrEmpty(fileName))
                {

                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        var fileStream = new FileStream(fileName, FileMode.Open);
                        response.Content = new StreamContent(fileStream);
                        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        response.Content.Headers.ContentDisposition.FileName = fileName;
                        return response;
                        //return ResponseMessage(response);
                }
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
            catch (Exception ex)
            {

                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }

Angular Service:

public getFile(filePath:string): Observable<Blob>{
    console.log(filePath);
    let path = 'http://localhost:19090/api/testAPI/DownLoadFile/testfile.csv';
    let options = new RequestOptions({responseType: ResponseContentType.Blob });
    return this._http.get(path, {responseType: 'blob'})
    .pipe(
      catchError(this.handleError));

  }

Component Code: My application uses Kendo Grid.

private downloadFile( dataItem: any):void{
  this._sharedService.getFile(dataItem.test_file)
  .subscribe(
     (data:Blob) => {
       saveAs(data, `Test_1.csv`); // from file-saver library
      },
     (err: any) => {
        console.log(`Unable to save file ${JSON.stringify(err)}`)}
    );
}

This code does download a csv file but it appears as :

   {"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["text/csv"]},{"key":"Content-Disposition","value":["attachment; filename=\"c:\\temp\\blaze.csv\""]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

What am I doing wrong? Any pointers?

These are some of the links I used to troubleshoot:

How do I download a file with Angular2

Angular download csv file with Web Api 2

UPDATE:

Thanks to this link - https://expertcodeblog.wordpress.com/2018/08/13/asp-net-core-angular-how-to-download-file-from-api-controller/

I was able to solve my problem. I updated my Controller code and I am able to download the file.

like image 546
ProgSky Avatar asked Nov 06 '22 20:11

ProgSky


1 Answers

As per my update, I was able to update my controller and that solved my issue. No change on Client code.

public async Task<IActionResult> DownloadFile(string filename)
        {
            try
            {
                string file = @"c:\temp\test.csv";

                var memory = new MemoryStream();
                using (var stream = new FileStream(file, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }

                memory.Position = 0;
                return File(memory, GetMimeType(file), filename);
            }
            catch (Exception e)
            {
                return BadRequest(e);
            }
        }
like image 54
ProgSky Avatar answered Nov 14 '22 23:11

ProgSky