我有以下代码:
[HttpPost]
public ActionResult Create(Knowledgebase KB, HttpPostedFileBase file)
{
var KBFilePath = "";
if (ModelState.IsValid)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(KB.KnowledgebaseTitle);
var path = Path.Combine(Server.MapPath("~/Resources/KBArticles"), fileName + ".pdf");
KBFilePath = path;
file.SaveAs(path);
}
KB.KnowledgebaseLink = KBFilePath;
db.Knowledgebases.Add(KB);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
链接是存储在以C:/开头的数据库中的文件路径。
在另一页上,我可以查看记录的内容。当我单击将其保存在C:/上的链接时,Chrome会显示“无法加载本地资源”。我保存到ASP.NET应用程序目录中的Resources文件夹中。反正这吗?
编辑从此视图提供页面:
public ActionResult Suggestions(String Tag)
{
return View();
}
编辑2-我将更改添加到我的视图中:
@{
string tag = "<td><a href=" + "~/Content/Files/" + ">" + item.Title.Replace(" ", "") + ".pdf" + "</a>" + "</td>";
}
@Html.Raw(tag)
浏览器地址栏中的请求文件是
http://localhost:62165/Incident/~/Content/Files/
现在我收到HTTP错误404.0找不到错误
尝试将文件保存在Content文件夹中。您可以创建一个子文件夹“内容/文件”。将文件放在此处。然后生成如下链接:
<a href="~/Content/Files/file1.pdf">File1</a>
或使用下载属性(如果要直接下载):
<a href="~/Content/Files/file1.pdf" download>File1</a>
。
大多数Web服务器都配置为拒绝对内容文件夹之外的内容的请求。可以在配置文件中进行修改,但是如果使用内容文件夹,则更容易(更安全)。这是基于我的经验,如果有人认为我错了,请让我知道以解决我的问题。我总是很高兴学习新知识。
编辑1:如何a
动态生成标记
在视图中,您需要一个字符串变量link
来保存要显示的链接的文本,并需要另一个变量path
来保存路径(也许两者都是从控制器中的db加载的)。然后,您可以像下面这样手动构建标记:
@{
string tag = "<a href=" + path + ">" + link + "</a>";
}
@Html.Raw(tag)
编辑2:处理网址中的空格。
您需要使用Html.Content
来获取正确的相对网址。
@{
string link = item.Title;
string path = Url.Content("~/Content/Files/") + link.Replace(" ", "%20") + ".pdf";
string tag = "<a href=" + path + ">" + link + "</a>";
}
@Html.Raw(tag)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句