-1

I am trying to download a file by clicking a button but instead of getting my file as "myFile.csv" the file that returns is called "download" without any extension. I have tried the following solution as well Download text/csv content as files from server in Angular

This is server response

            var result = engine.WriteString(recs);
            response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(Encoding.UTF8.GetBytes(result)) };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = String.Format("TVF_Export_{0}.csv", DateTime.Now.ToShortDateString())
            };
            return response;

Client code

        $http.post(url, filters).success(function (data, status, headers, config) {
        console.log(data);
        var hiddenElement = document.createElement('a');

        hiddenElement.href = 'data:attachment/csv,' + encodeURI(data);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'myFile.csv';
        hiddenElement.click();


    }).error(function (data, status, headers, config) {
        console.log('[DEBUG] error ' + data);
    });
Community
  • 1
  • 1
eugenekgn
  • 1,652
  • 2
  • 17
  • 38
  • Some more information would be useful. Where are you downloading your file from, what http-headers are set from the server-side? – RononDex May 27 '14 at 12:39
  • the data object is just a string content – eugenekgn May 27 '14 at 12:40
  • That's not what is important. You have to tell us, how the server responds to your download request. What HTTP headers are sent to you from the server? Normally it's the HTTP-headers that control such stuff – RononDex May 27 '14 at 15:48

1 Answers1

1

If you have control over server response, then you can ensure the following header is set in response:

Content-Disposition: attachment; filename=myFile.csv;

You should also specify Content-Type: text/csv or this:

Content-Type: application/force-download
col
  • 397
  • 3
  • 10