开发者

C#/.Net: Returning a file to the browser?

Following this question it was recommend that I should create a server side file that can return a file from the fil开发者_运维问答e system. How would I go about doing this in c# and .net. I imagine I pass the filename as a query string, this is read by the page and the file returned. Not really sure where to start on this from a codding point.


You can use the Response.WriteFile method to send the contents of the file, though this may fail with larger files.

Be careful not to allow any filename to be specified in your query string, as users could then use this to access any file on your server. Better to have a database of files that are allowed with a name for each one, and look up a name supplied in the query string against this database to get the filename.


I would recommend reading the file in as a byte[] and sending it out with it's content-type and content-disposition set in the response and then just perform a response.binarywrite and a 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();

The response portions will need adjusting according to your own delivery platform (separate page, in iframe, etc). You may not want to ClearHeaders() for instance.


This thread has my suggestion for serving files outside the web root. It uses a buffer to keep memory usage down.


You can use Response.TransmitFile which is useful for transmitting large files. After this you should use Response.Flush(). The Content type is here for zip file.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜