我在微软网站上使用Razor和C#进行文件上传时遵循了这个示例。
如果我有多个文件上传按钮,C#代码如何知道上传的文件来自哪个按钮?根据上传文件的按钮,我将把文件保存到特定的文件夹。
https://docs.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>发布于 2017-08-14 06:55:55
这样做的方法是将按钮命名为相同的名称,但赋予它们不同的值。然后,您可以执行case语句,并根据该值指导逻辑。
剃刀
@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" />
}控制器
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();
}发布于 2017-08-14 09:17:42
我遇到了类似的问题,结果代码如下:
剃刀
//BeginForm and other staff
@foreach (var d in Model.Types)
{
<input type="file" name="doc:@d.Id:upload" />//@d.Id is the key point
<button formenctype="multipart/form-data"
type="submit" formaction="/MyController/uploaddoc"
name="typeid" formmethod="post" value="@d.Id">//this way I send Id to controller
Upload
</button>
}MyController
[HttpPost]
[ValidateAntiForgeryToken]
[Route("mycontroller/uploaddoc")]//same as formaction
public async Task<ActionResult> UploadDoc(FormCollection data, int typeid)
{
//restore inpput name
var fl = Request.Files["doc:" + typeid.ToString() + ":upload"];
if (fl != null && fl.ContentLength > 0)
{
var path = Server.MapPath("~/app_data/docs");
var fn = Guid.NewGuid().ToString();//random name
using (FileStream fs = System.IO.File.Create(Path.Combine(path, fn)))
{
await fl.InputStream.CopyToAsync(fs);
}
}
}https://stackoverflow.com/questions/45664625
复制相似问题