【问题标题】:Uploading multiple images + text fields in ASP.NET MVC在 ASP.NET MVC 中上传多个图像 + 文本字段
【发布时间】:2010-10-10 22:01:12
【问题描述】:

我是 ASP.net MVC 的新手,所以请在你的回答中尽可能描述性:)

让我简化我正在尝试做的事情。想象一下,我有一个表格,您想在其中输入有关汽车的一些信息。字段可能是:品牌、型号、年份、Image1、Image2。

表单底部是一个“保存”按钮。关联的 Controller 方法会将 Image1 和 Image2 保存到磁盘,获取它们的文件名并将它们与汽车模​​型相关联,然后将它们保存到数据库中。

有什么想法吗?

谢谢大家!

编辑

winob0t 让我大部分时间到达那里。唯一突出的问题是:Image1 和 Image2 不是必填字段,所以我现在可以保存 0,1 或 2 张图像;但如果用户只上传 1 张图片,我无法知道它是来自 imageUpload1 还是 imageUpload2。

再次感谢任何帮助!

【问题讨论】:

    标签: asp.net-mvc file-upload


    【解决方案1】:

    在您的控制器中,您可以通过以下方式访问上传的文件:

        if(Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
            HttpPostedFileBase postFile = Request.Files.Get(0);
            string filename = GenerateUniqueFileName(postFile.FileName);
            postFile.SaveAs(server.MapPath(FileDirectoryPath + filename));
        }
    
    protected virtual string GenerateUniqueFileName(string filename) {
    
        // get the extension
        string ext = Path.GetExtension(filename);
        string newFileName = "";
    
        // generate filename, until it's a unique filename
        bool unique = false;
    
        do {
            Random r = new Random();
            newFileName = Path.GetFileNameWithoutExtension(filename) + "_" + r.Next().ToString() + ext;
            unique = !File.Exists(FileDirectoryPath + newFileName);
        } while(!unique);
        return newFileName;
    }
    

    文本字段将照常到达您的控制器操作,即 Request.Form[...]。请注意,您还需要将表单上的 enctype 设置为“multipart/form-data”。听起来您对 ASP.NET MVC 了解得足够多,可以完成剩下的工作。另请注意,您可以按如下方式在 aspx 视图中声明您的表单标签,但如果您愿意,也可以使用更传统的方法。

    <% using(Html.BeginForm<FooController>(c => c.Submit(), FormMethod.Post, new { enctype = "multipart/form-data", @id = formId, @class = "submitItem" })) { %> 
    
    <% } %>
    

    【讨论】:

    • 你让我成功了一半!只有一个小问题:不能保证 Image1 和 Image2 存在。那么如果用户只提供 Image2 而不是 Image1 怎么办?有没有办法知道它来自哪个上传控件?
    • 而不是 Request.Files[0] 你应该能够使用 Request.Files["formInputname"]
    • if(Request.Files["formInputname"] != null && Request.Files["formInputname"].ContentLength > 0)
    • 啊啊啊……我想我是个假人。我正在尝试表单 [“formInputName”]。谢谢!
    【解决方案2】:

    这是我的解决方案,上面的答案对我的情况不太适用。它不关心表单细节,并允许多次上传。

        for (int i = (Request.Files.Count - 1); i >= 0; i--)
        {
              if (Request.Files != null && Request.Files[i].ContentLength > 0)
              {
                   string path = this.Server.MapPath("~/Content/images/");
                   string filename = Path.GetFileName(Request.Files[i].FileName);
                   string fullpath = Path.Combine(path, filename);
                   Request.Files[i].SaveAs(fullpath);
               }
         }
    

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2014-11-04
      • 2012-05-11
      • 2018-08-28
      • 2016-05-26
      • 1970-01-01
      • 2020-08-06
      • 2011-02-07
      • 2013-10-03
      相关资源
      最近更新 更多