【问题标题】:Why doesn't the hyperlink open the file?为什么超链接打不开文件?
【发布时间】:2015-07-06 18:49:20
【问题描述】:

早期的开发人员使用标签放置此代码,并在运行时将其转换为超链接。

<asp:Label ID="lbl_Attachment" runat="server">
</asp:Label>

lbl_Attachment.Text = "<a href='../Uploads/" + 
                      ds_row["Attachment"].ToString() + "'>" + 
                      ds_row["Attachment"].ToString() + "</a>";

但这不起作用。所以我将代码更改为以下,以在新的浏览器选项卡中打开任何文件(图像/pdf/word),错误仍然存​​在:

      hyperlinkAppDoc.NavigateUrl = 
          ResolveUrl("../Uploads/" + 
          ds_row["Attachment"].ToString());
      hyperlinkAppDoc.Target = "_blank";  

我可以做些什么来解决这个问题? MIME 类型在 IIS 中可用。


更新: 我正在尝试一种不同的方法。但是Server.MapPath 指向本地驱动器而不是 wwwroot。如何将路径指向 wwwroot 文件夹?

string pdfPath = Server.MapPath("~/SomeFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(pdfPath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);

【问题讨论】:

    标签: asp.net file c#-4.0 hyperlink


    【解决方案1】:

    您可以使用asp.hyperlink。喜欢关注

    &lt;asp:HyperLink id="hyperlink1" NavigateUrl="&lt;set_from_code_behind&gt;" Text="Text to redirect" runat="server"/&gt;

    并从后面的代码中设置 NavigateUrl,如下所示。

    hyperlink1.NavigateUrl= "Uploads/" + ds_row["Attachment"].ToString();

    【讨论】:

    • 那么错误是什么?那个时候数据阅读器关闭了吗?您可以尝试删除.. 吗?
    • 我是说使用/,如果它在同一个位置,你可以试试~,或者让我知道相对于父路径的位置在哪里。
    • @aspiring,更新答案,检查,它应该可以工作 - 删除 ../
    • 您需要确保您能够使用http://localhost/upload/somefile.pdf 访问网址并检查生成的网址是否与上面相同,我可以在屏幕截图中看到,@987654329 中有一些制表符/空格@ 和 /upload...,你需要检查一下。
    • 好的,那么这意味着文件实际上不存在-我已经在上面的评论中说过-http://localhost/upload/somefile.pdf,请检查这是否有效,假设您在wwwroot\TheSite\Uploads\somefile.pdf中有文件。
    【解决方案2】:

    在你的情况下,我建议你在你的网络配置文件的&lt;appSettings&gt;标签中添加一个键。

    <appSettings>    
        <add key="WebsiteURL" value="http://localhost:1234/WebsiteName/"/>
    </appSettings>
    

    下一步是在 .Aspx 文件中创建一个超链接。

    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"></asp:HyperLink>
    

    在代码后面连接 AppSettings Key + 从根目录下载文件路径。

    string base_path = ConfigurationSettings.AppSettings["WebsiteURL"];
    HyperLink1.NavigateUrl = base_path + "Uploads/" + ds_row["Attachment"].ToString();
    

    如果您有任何问题,请告诉我。

    【讨论】:

    • 没什么特别的,我在 8 个月前遇到了这个 404 错误,我就这样解决了。当我继续直播时,我刚刚将 localhost url 替换为 live url,它仍然可以正常工作。
    【解决方案3】:

    所有的汗水都是由于路径问题。旧代码和新代码都有效。无需网络客户端代码。

    上传路径在这里设置:

    public static string UploadDirectory = ConfigurationManager.AppSettings["UploadDirectory"];

    它指向根目录中与应用程序所在位置不同的目录。因此,这些文件仅被上传但从未被拾取。

    我现在将其更改为 AppDomain.CurrentDomain.BaseDirectory。在我们与用户交谈后,我们将进行相应的设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-27
      相关资源
      最近更新 更多