问题
Earlier developer had put this code using a label and it was turned into a hyperlink during the run time.
<asp:Label ID="lbl_Attachment" runat="server">
</asp:Label>
lbl_Attachment.Text = "<a href='../Uploads/" +
ds_row["Attachment"].ToString() + "'>" +
ds_row["Attachment"].ToString() + "</a>";
But this is not working. So I changed the code to the following to open the any file (image/pdf/word) in a new browser tab and the error persists:
hyperlinkAppDoc.NavigateUrl =
ResolveUrl("../Uploads/" +
ds_row["Attachment"].ToString());
hyperlinkAppDoc.Target = "_blank";
What can I do to fix this issue? MIME types are available in the IIS.
UPDATE:
I am trying out a different approach. However the Server.MapPath is poiting at local drive instead of wwwroot. How can I point the path to wwwroot folder?
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);
回答1:
You could have used asp.hyperlink. Like following
<asp:HyperLink id="hyperlink1" NavigateUrl="<set_from_code_behind>" Text="Text to redirect" runat="server"/>
And set NavigateUrl from code behind as following.
hyperlink1.NavigateUrl= "Uploads/" + ds_row["Attachment"].ToString();
回答2:
In your situation, I suggest you to add one key in <appSettings> tag in your web config file.
<appSettings>
<add key="WebsiteURL" value="http://localhost:1234/WebsiteName/"/>
</appSettings>
Next step is to take one hyperlink in your .Aspx file.
<asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"></asp:HyperLink>
In code behind concatenate AppSettings Key + Download file path from root.
string base_path = ConfigurationSettings.AppSettings["WebsiteURL"];
HyperLink1.NavigateUrl = base_path + "Uploads/" + ds_row["Attachment"].ToString();
Please let me know if you have any questions.
回答3:
All the sweat was due to path issue. Old code and new code works. There's no need for a web client code.
The upload path was set here:
public static string UploadDirectory = ConfigurationManager.AppSettings["UploadDirectory"];
It was pointing to a different directory in the root other than where the application was. Therefore the files were only uploaded but never picked up.
I changed it to AppDomain.CurrentDomain.BaseDirectory for now. After we talk with the users, we will set it accordingly.
来源:https://stackoverflow.com/questions/29910618/why-doesnt-the-hyperlink-open-the-file