下载时获取文件名
我们提供保存在我们的数据库中的文件,检索它们的唯一方法是通过它们的id
如:
www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23
当我使用WebClient类时,一切都正常工作。
我面临的问题只有一个:
我怎样才能获得真实的文件名?
我的代码看起来像这个atm:
WebClient client = new WebClient (); string url = "www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23"; client.DownloadFile(url, "IDontKnowHowToGetTheRealFileNameHere.txt");
我所知道的只是身份证 。
当我尝试从浏览器访问url
时,这不会发生,因为它得到了正确的名称=> DownloadedFile.xls 。
获得正确答案的正确方法是什么?
我有同样的问题,我找到了这个类: System.Net.Mime.ContentDisposition 。
using (WebClient client = new WebClient()){ client.OpenRead(url); string header_contentDisposition = client.ResponseHeaders["content-disposition"]; string filename = new ContentDisposition(header_contentDisposition).FileName; ...do stuff... }
类文档建议它用于电子邮件附件,但它在我以前测试的服务器上工作正常,并且避免解析非常好。
假设服务器已应用content-disposition标头,以下是所需的完整代码:
using (WebClient client = new WebClient()) { using (Stream rawStream = client.OpenRead(url)) { string fileName = string.Empty; string contentDisposition = client.ResponseHeaders["content-disposition"]; if (!string.IsNullOrEmpty(contentDisposition)) { string lookFor = "filename="; int index = contentDisposition.IndexOf(lookFor, StringComparison.CurrentCultureIgnoreCase); if (index >= 0) fileName = contentDisposition.Substring(index + lookFor.Length); } if (fileName.Length > 0) { using (StreamReader reader = new StreamReader(rawStream)) { File.WriteAllText(Server.MapPath(fileName), reader.ReadToEnd()); reader.Close(); } } rawStream.Close(); } }
如果服务器没有设置此标头,请尝试调试并查看您拥有的ResponseHeaders,其中一个可能包含您想要的名称。 如果浏览器显示名称,它必须来自某个地方 .. 🙂
你需要通过以下方式查看content-disposition
标题:
string disposition = client.ResponseHeaders["content-disposition"];
一个典型的例子是:
"attachment; filename=IDontKnowHowToGetTheRealFileNameHere.txt"
您可以使用HTTP content-disposition
标头为您提供的内容建议文件名:
Content-Disposition: attachment; filename=downloadedfile.xls;
因此,在AwesomeSite.aspx
脚本中,您将设置content-disposition
标头。 在您的WebClient
类中,您将检索该标头以按照AwesomeSite
站点的建议保存文件。
我用wst的代码实现了这一点。
以下是在c:\ temp文件夹中下载url文件的完整代码
public static void DownloadFile(string url) { using (WebClient client = new WebClient()) { client.OpenRead(url); string header_contentDisposition = client.ResponseHeaders["content-disposition"]; string filename = new ContentDisposition(header_contentDisposition).FileName; //Start the download and copy the file to the destinationFolder client.DownloadFile(new Uri(url), @"c:\temp\" + filename); } }