Downloading the file with the answer does not show the file size

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 it works, but when it does not show the file size, in firefox it shows the file size -1 and in chrome, etc. it does not display file size at all. How to show file size?

+4
source share
2 answers

Have you tried to do this:

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

If the length of the content is set, the web browser will display a progress bar during download. 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 they are, so they will not cancel the download and do not start it, or, even worse, just leave your site. Contact

+6
source

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

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

If you are streaming a file, your code might look like this:

 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 eg application/zip>"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("file") { FileName = "<destination file name>" }; return response; 
+1
source

Source: https://habr.com/ru/post/1384691/


All Articles