我想执行上传&从数据库下载。在MVC核心中,它工作正常,但我无法将MVC控制器的mathod转换为Razor Pages的Handler方法怎么做。如果有人帮忙,我会很高兴的。以下是关于我的应用程序的更多详细信息
MVC核心的控制器方法
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("file not selected");
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
file.GetFilename());
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return RedirectToAction("Files");
}
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(
Directory.GetCurrentDirectory(),
"wwwroot", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
如何在Razor页面中表示上述方法
按照以下步骤尝试更改Razor页面:
- 在
Pages
中添加File
Razor页面 -
其内容为
public class FileModel : PageModel { public void OnGet() { } [BindProperty] public IFormFile FormFile { get; set; } [IgnoreAntiforgeryToken] public async Task<IActionResult> OnPostUploadFileAsync() { return RedirectToPage("Index"); } public async Task<IActionResult> OnGetDownloadAsync(string filename) { if (filename == null) return Content("filename not present"); var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot", filename); var memory = new MemoryStream(); using (var stream = new FileStream(path, FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; return File(memory, "application/octet-stream", Path.GetFileName(path)); } }
-
其视图为
@page @model TestRazor.Pages.FileModel @{ ViewData["Title"] = "File"; } <h2>File</h2> <div class="row"> <div class="col-md-4"> <form method="post" asp-page-handler="UploadFile" enctype="multipart/form-data"> <div class="form-group"> <label asp-for="FormFile" class="control-label"></label> <input asp-for="FormFile" type="file" class="form-control" style="height:auto" /> <span asp-validation-for="FormFile" class="text-danger"></span> </div> <input type="submit" value="Upload" class="btn btn-default" /> </form> </div> </div>
-
对
OnGetDownloadAsync
的请求是https://localhost:44332/file?handler=download&filename=test.txt
-
对于上传加载文件,转到
https://localhost:44332/file
,然后单击上传按钮上传文件
有关Razor页面的更多信息,请参阅ASP.NET Core 中的Upload files to a Razor page