Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading a file with response doesn't show a filesize

Tags:

html

c#

asp.net

I have this piece of code in a function:

Response.Clear();
Response.ContentType = "text/xml; charset=utf-8";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xml");
// Put xml into response here
Response.End();

And this works, but, when it, it doesn't show a file size, in firefox it shows the filesize -1 and in chrome and ie it doesn't show a file size at all. How can I show the file size?

like image 465
NomenNescio Avatar asked Feb 22 '23 05:02

NomenNescio


2 Answers

Did you try giving this:

Response.AddHeader("Content-Length", someBytes.Length.ToString());

If the content-length is set the web browser will show a progress bar while downloading. This is a very important usability feature for medium and large files, and you really want it. You want your user to know how far along they are, so they don't cancel the download and start it over, or worse just abandon your site. Refer

like image 112
FosterZ Avatar answered Mar 02 '23 18:03

FosterZ


If your Response is of type System.Net.Http.HttpResponseMessage, you can insert a Content-Length header by using:

response.Content.Headers.ContentLength = <length in bytes>;

If you are stream a file your code could look like:

FileStream fileStream = File.Open("<source file name>", FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentLength = fileStream.Length;
response.Content.Headers.ContentType = 
  new MediaTypeHeaderValue("<media type e.g. application/zip>");
response.Content.Headers.ContentDisposition = 
  new ContentDispositionHeaderValue("file")
    {
      FileName = "<destination file name>"
    };
return response;
like image 41
Yves Tkaczyk Avatar answered Mar 02 '23 17:03

Yves Tkaczyk