WITH#/. Net: return file to browser?

Following this question , I was encouraged to create a server-side file that can return a file from the file system. How I will do it in C # and .net. I assume that I pass the file name as a query string, this is read by the page and the returned file. Not quite sure where to start from the vanishing point.

+3
source share
4 answers

You can use the Response.WriteFile method to send the contents of the file, although this can happen with large files.

Be careful not to include the file name in the query string, as users could use this to access any file on your server. It is better to have a database of files that are resolved with a name for each, and find the name indicated in the query string for that database to get the file name.

+5
source

I would recommend reading the file as a byte [] and sending it with the content and content type in response, and then just execute response.binarywrite and response.flush:

Byte[] bytes = null; 

try
{

    if(!FileExists(_filename)) return null;

    Byte[fs.Length] bytes 

    // get file contents
    using(System.IO.FileStream fs = System.IO.File.Open(_file, FileMode.Open, FileAccess.Read))
    {
        fs.Read(bytes, 0, fs.Length);
    }

}
catch(Exception ex)
{
            System.Text.ASCIIEncoding oEncoder = new System.Text.ASCIIEncoding();
            Byte[] bytes = oEncoder.GetBytes(ex.Message);

}

Context.Response.Buffer = false;
Context.ClearContent();
Context.ClearHeaders();
Context.ContentType = "application/octet-stream"; // Change this type as necessary
Context.AddHeader("Content-Length", bytes.Length.ToString());
Context.AddHeader("content-disposition", String.Format("inline; filename={0}", filename));
Context.Response.BinaryResult(bytes);
Context.Response.Flush();

Parts of the response will need to be adjusted according to your own delivery platform (separate page, in iframe, etc.). For example, you may not want ClearHeaders ().

+1
source
+1
source

You can use Response.TransmitFile, which is useful for transferring large files. After that you should use Response.Flush (). The content type is here for the zip file.

Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", "attachment; filename = D:\Splitted Parts.zip");
Response.TransmitFile(zipFileName);
Response.Flush();
+1
source

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


All Articles