gpt4 book ai didi

c# - 上传和查看文件 ASP.NET MVC 5

转载 作者:可可西里 更新时间:2023-11-01 08:55:41 25 4
gpt4 key购买 nike

我有这个代码:

    [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 显示“无法加载本地资源”。我正在保存到 Resources 文件夹中,该文件夹是我的 ASP.NET 应用程序目录的一部分。无论如何围绕这个?

编辑该页面从此 View 提供:

public ActionResult Suggestions(String Tag)
{
return View();
}

编辑 2 - 我将更改放在我的 View 中:

@{
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 未找到错误

最佳答案

这是一个完整的示例,展示了如何上传文件并通过链接提供文件以供下载。

创建一个空的 MVC 项目。我使用 MVC 4,但它应该适用于 MVC 5。

Controller :

HomeController 中,我们将有一个操作 Index,它将显示可供下载的文件列表和上传新文件的选项。

Action Index GET:

  • 找到“Content/Files/”的路径。
  • 获取该文件夹中所有文件的列表。
  • 将该列表用作Index View 的模型。

Action 索引 POST:

  • 找到“Content/Files/”的路径。
  • 创建一个临时数组来存储文件的内容。
  • 读取内容到缓冲区。
  • 将内容写入文件夹“Content/Files/”中的文件。

代码:

public class HomeController : Controller
{
public ActionResult Index()
{
var path = Server.MapPath("~/Content/Files/");

var dir = new DirectoryInfo(path);

var files = dir.EnumerateFiles().Select(f => f.Name);

return View(files);
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
var path = Path.Combine(Server.MapPath("~/Content/Files/"), file.FileName);

var data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);

using (var sw = new FileStream(path, FileMode.Create))
{
sw.Write(data, 0, data.Length);
}

return RedirectToAction("Index");
}

}

查看:

在 View 中,我们需要生成一个包含文件链接的列表。这里我们需要处理包含空格的文件名并将它们替换为“%20”。

上传文件的表单很简单。只需一个用于获取文件的输入标签和一个用于发送表单的按钮。

@model IEnumerable<string>

@{
ViewBag.Title = "Index";
}

<h2>Files</h2>

<ul>
@foreach (var fName in Model)
{
var name = fName;
var link = @Url.Content("~/Content/Files/") + name.Replace(" ", "%20");

<li>
<a href="@link">@name</a>
</li>
}
</ul>

<div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="File" name="file" id="file" value="Choose File"/>
<button type="submit">Upload</button>
}
</div>

结果应该是:

Index view

关于c# - 上传和查看文件 ASP.NET MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22592226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com