开发者

How to designate the name of a file that a user downloads via an ASHX downloader?

开发者 https://www.devze.com 2023-04-10 09:43 出处:网络
This is my first time writing code that allows a user to开发者_开发问答 download a file uploaded by another user.

This is my first time writing code that allows a user to开发者_开发问答 download a file uploaded by another user.

I've written an ASHX file, download.ashx, with code that looks like this:

s = context.Request.QueryString.ToString();
byte[] buffer = new ReplacementTicketFileIO().GetSpecifiedFile(s);
context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.End();

When a user clicks on a link to download.ashx with the appropriate querystring, the file is downloaded, but the browser wants to display the content in the browser window. If the user right-clicks on the link, he can download the file, but the name of the file defaults to download.ashx.

I would like to accomplish two things:

1) I would like to be able to specify the default name of the file downloaded on the user's device based on the querystring.

For instance, if the user clicks on download.ashx?linkedfile=car.pdf, I would like for the browser to default to car.pdf for the name of this file.

2) I would like for the browser to default to saving the link, as opposed to opening the link in the browser window.

Is it reasonable for me to want to do this, or is there a better way to download files? Please let me know.


Set the Content-Disposition HTTP header. E.g.

Content-Disposition: attachment; filename=hello.jpg

You can do that in C# using:

 Response.AddHeader("Content-Disposition", "attachment; filename=hello.jpg");


Here is something I have for excel files and I believe it forces a download rather than a new window. There is a page property for QueryString. You would just need to capture the QueryString and use it in this code as well as determining the content type. The String.Format will give you clean code.

private string _ExcelFilename
{
        get
{
    return (Request.QueryString["xls"] != null) ? Request.QueryString"xls"] : "bis";
}
}

Page.Response.Clear();
Page.EnableViewState = false;
Page.Response.Clear();
Page.Response.ContentType = "application/vnd.ms-excel";
Page.Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}_{1}.xls", _ExcelFilename, DateTime.Now.ToString("yyyyMMdd")));
Page.Response.Write(excel);
Page.Response.Flush();
Page.Response.End();
0

精彩评论

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

关注公众号