c# - ASP.NET Razor 文件上传

标签 c# asp.net razor file-upload

我在 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/

相关文章:

asp.net - 在 Web API 中将数组标题添加到 Linq-to-SQL-to-JSON

asp.net-mvc - T4 模板中的 RenderPartial()

asp.net-mvc - 在 div 的 Style 属性中使用 MVC3 ViewData

c# - 将路由中的参数读取到 ViewBag 中,以在一个地方获取所有 View

c# - ILogger 的隐式范围

c# - 在对象的并行 linq 中指定任务超时

C# - 获取文件夹后代的 LastWriteTime

asp.net - InProc session 数据消失

c# - 为什么静态变量在 Asp.Net 中消亡

c# - 将数据中继到一个或多个客户端的套接字服务器。 C#