继续学习微软的上传文件示例,学习支持目录浏览、删除文件、下载文件等功能,并将之迁移到之前创建的webapp项目中。
上述与文件操作相关的功能主要采用PhysicalFileProvider类实现,该类用于使用磁盘上的文件系统查找文件。其实也可以采用System.IO命名空间下的文件和文件夹相关类来获取文件信息,但没有PhysicalFileProvider用的方便,且后者可以以注册服务方式供项目中其它类调用。
通过调用PhysicalFileProvider类中的GetDirectoryContents函数获取指定目录下的文件和文件夹信息,并通过绑定模型方式将清单传递并显示在页面中。支持目录浏览、删除文件、下载文件等功能的后台代码如下所示(从微软示例程序中剥离的代码)
public IDirectoryContents PhysicalFiles { get; private set; }
public async Task OnGetAsync()
{
PhysicalFiles = _fileProvider.GetDirectoryContents(string.Empty);
}
public IActionResult OnGetDownloadPhysical(string fileName)
{
var downloadFile = _fileProvider.GetFileInfo(fileName);
return PhysicalFile(downloadFile.PhysicalPath, MediaTypeNames.Application.Octet, fileName);
}
public IActionResult OnGetDeletehysical(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return RedirectToPage("/Index");
}
IFileInfo RemoveFile = _fileProvider.GetFileInfo(fileName);
if (RemoveFile.Exists)
{
System.IO.File.Delete(RemoveFile.PhysicalPath);
}
PhysicalFiles = _fileProvider.GetDirectoryContents(string.Empty);
return Page();
}
前端页面中的代码也是将微软示例中不同页面中拼到一起的,本文测试可以正常运行。
<div>
<form enctype="multipart/form-data" method="post">
<dl>
<dt>
<label asp-for="MultiFiles"></label>
</dt>
<dd>
<input asp-for="MultiFiles" type="file" multiple accept=".pdf"/>
<span asp-validation-for="MultiFiles"></span>
</dd>
</dl>
<input asp-page-handler="Upload" class="btn" type="submit" value="上传文件" />
</form>
<p class="result">
@Model.Result
</p>
</div>
<div>
<h1>Files stored on disk</h1>
@if (Model.PhysicalFiles.Count() == 0)
{
<p>
No files are available. Visit one of the file upload scenario pages to upload one or more files.
</p>
}
else
{
<table>
<thead>
<tr>
<th></th>
<th>
Name
</th>
<th>
Size (bytes)
</th>
<th>
<code>PhysicalFileResult</code> from storage
</th>
</tr>
</thead>
<tbody>
@foreach (var file in Model.PhysicalFiles) {
<tr>
<td>
<a asp-page-handler="Deletehysical" asp-route-fileName="@file.Name">Delete</a>
</td>
<td>
<b>@file.Name</b><br>
</td>
<td class="text-center">
@file.Length.ToString("N0")
</td>
<td class="text-center">
<a asp-page-handler="DownloadPhysical" asp-route-fileName="@file.Name">Download</a>
</td>
</tr>
}
</tbody>
</table>
}
</div>
最后是程序运行效果,如下图所示:
参考文献:
[1]https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.fileproviders.physicalfileprovider?view=dotnet-plat-ext-6.0
[2]https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0