我在 MS 网站上使用 Razor 和 C# 来关注文件上传的这个例子。
如果我有多个文件上传按钮,C# 代码如何知道上传的文件来自哪个按钮?根据上传文件的按钮,我会将文件保存到特定文件夹。
https://learn.microsoft.com/en-us/aspnet/web-pages/overview/data/working-with-files
@using Microsoft.Web.Helpers;
@{
var fileName = "";
if (IsPost) {
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
}
}
<!DOCTYPE html>
<html>
<head>
<title>FileUpload - Single-File Example</title>
</head>
<body>
<h1>FileUpload - Single-File Example</h1>
@FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Upload")
@if (IsPost) {
<span>File uploaded!</span><br/>
}
</body>
</html>
最佳答案
这样做的方法是为按钮命名相同,但给它们不同的值。然后,您可以执行一个 case 语句并根据值指导逻辑。
Razor
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FirstUpload" />
<input type="submit" name="submitID" id="submitID" value="Upload1" />
<input type="file" name="SecondUpload" />
<input type="submit" name="submitID" id="submitID" value="Upload2" />
}
Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection collection)
{
string btn = Request.Params["submitID"];
switch (btn)
{
case "Upload1":
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
}
break;
case "Upload2":
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
}
break;
}
return View();
}
关于c# - ASP.NET Razor 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664625/