【问题标题】:adding download to an anchor tag using C#使用 C# 将下载添加到锚标记
【发布时间】:2013-10-29 06:21:30
【问题描述】:

所以基本上html看起来像这样

<a href='test.pdf' Download>download test</a>

但我需要用 C# 来制作它,到目前为止我所拥有的是

HtmlAnchor link = new HtmlAnchor();
link.Href = "test.pdf";
link.innerText = "download test";

如何放入“下载”部分,以便当您单击链接时它实际上会下载文件而不是链接到它?

【问题讨论】:

  • 只是为了说明这一点。在您的示例中,PDF 文件在您的浏览器中打开,而不是显示保存文件对话框?
  • 显示保存或打开对话框。在 Html 代码中它会显示该框,但在 C# 中它不会。
  • link.Attributes.Add("下载", "下载");你会喜欢那个属性,比如 Download="Download"
  • 在您使用 C#HtmlAnchor 时,能否发布您生成的 html 代码(检查 Web 浏览器页面)?
  • 生成的代码就是这样 --> 下载测试 现在我只需要下载部分...

标签: c# asp.net hyperlink


【解决方案1】:

您需要使用InnerHtml 而不是InnerText 以及&lt;b&gt; 用于粗体

link.InnerHtml = @"<b>download test</b>";

基于OP编辑编辑,

您需要在链接按钮单击事件上使用 Response.WriteFile,您可能会在此 post 中查找被询问的内容。

FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.WriteFile(fileInfo.FullName);
Response.End();

【讨论】:

  • 这甚至不是我问的问题......但我编辑了这个问题,所以现在应该更清楚了,我希望。
  • 是的,很抱歉我的问题含糊不清。但无论如何,将文件写入网站如何使其被下载?我不明白这将如何工作?
  • 嗯,我不确定它是如何工作的,但它确实如此,我很高兴 :) 谢谢
【解决方案2】:

试试这个:在你的 html 页面中,在 C# 中,写:litdoc.Text += "" + "download test" + "";在处理程序中:提到下载pdf文件的代码,就像:

    string file = "";
    file = context.Request.QueryString["file"]; 
    if (file != "")
    {
        context.Response.Clear(); 
        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("content-disposition", "attachment;filename="    +           Path.GetFileName(file));
        context.Response.WriteFile(file);
        context.Response.End();

    }

其中 path 是您下载 pdf 文件的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-15
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2015-07-12
    相关资源
    最近更新 更多