来自MVC5的.Net核心全新,那么下载文件如何与.NET Core一起使用?我尝试写下代码,但它有错误。提前感谢帮助者。
控制器
public ActionResult Download()
{
string[] files = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
for (int i = 0; i < files.Length; i++)
{
files[i] = Path.GetFileName(files[i]);
}
ViewBag.Files = files;
return View();
}
public FileResult DownloadFile(string fileName)
{
var filepath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
return File(filepath, LineMapping.GetMimeMapping(filepath), fileName);
}
查看
<h2>Downloads</h2>
<table>
<tr>
<th>File Name</th>
<th>Link</th>
</tr>
@for (var i =0; i <= Model.Count -1; i++) {
<tr>
<td>
@Model[i].ToString()
</td>
<td>
@Html.ActionLink("Download", "Download", new { ImageName=@Model[i].ToString() })
</td>
</tr>
}
答案 0 :(得分:1)
编写的代码甚至无法编译,因为Path.Combine
不返回文件列表。您还会在视图中看到解析错误,因为您引用了Model
,但您没有模型。此外,您的参数ImageName
与您的操作的参数名称不匹配。代码的其他几个问题(在数组上使用Count
- 使用Count()
或Length
。
我认为您正在尝试做这样的事情?
<强>控制器强>
public ActionResult Download()
{
string[] files = Directory.GetFiles(Path.Combine(_hostingEnvironment.WebRootPath, "uploads"));
for (int i = 0; i < files.Length; i++)
{
files[i] = Path.GetFileName(files[i]);
}
return View(files);
}
public FileResult DownloadFile(string fileName)
{
var filepath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads", fileName);
return File(filepath, "application/pdf", fileName);
}
查看强>
<table>
<tr>
<th>File Name</th>
<th>Link</th>
</tr>
@for (var i = 0; i <= Model.Length - 1; i++)
{
<tr>
<td>
@Model[i].ToString()
</td>
<td>
@Html.ActionLink("Download", "DownloadFile", new { fileName = @Model[i].ToString() })
</td>
</tr>
}
</table>