我想从数据库执行上载和下载。在 MVC Core 中,它正常工作,但是我无法转换MVC控制器方法输入到Razor Pages的Handler方法中。如何做到。如果有人帮助我将感到非常高兴。以下是有关我的应用程序的更多详细信息
MVC Core的控制器方法
[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));
}
答案 0 :(得分:0)
尝试按照以下步骤更改“剃刀页面”:
File
中添加Pages
剃刀页面其内容为
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
,然后单击“上传”按钮以上传文件
有关“剃刀”页面的更多信息,请参见Upload files to a Razor Page in ASP.NET Core