【问题标题】:Uploading an image using ASP.NET MVC使用 ASP.NET MVC 上传图像
【发布时间】:2010-11-25 15:49:14
【问题描述】:

我需要上传图像作为 MVC 应用程序中创建操作的一部分。

图像将存储在文件服务器中,数据库将包含一个路径。

我打算用下面的标签来获取文件:

> <input type="file" id="MyImage" name="MyImageName" />

如何在控制器操作中访问和保存它?

【问题讨论】:

    标签: asp.net-mvc file-upload upload


    【解决方案1】:

    我把它放在一个 BaseController 类中,我的所有控制器都从该类继承:

        // this just prefixes datetime as yyyyMMddhhmmss to the filename, to
        // be use that no name collision will occur.
        protected static String PrefixFName(String fname)
        {
            if (String.IsNullOrEmpty(fname))
            {
                return null;
            }
            else
            {
                return String.Format("{0}{1}",
                                     DateTime.Now.ToString("yyyyMMddhhmmss"),
                                     fname);
            }
        }
    
        protected String SaveFile(HttpPostedFileBase file, String path)
        {
            if (file != null && file.ContentLength > 0)
            {
                if (path == null)
                {
                    throw new ArgumentNullException("path cannot be null");
                }
                String relpath = String.Format("{0}/{1}", path, PrefixFName(file.FileName));
                try
                {
                    file.SaveAs(Server.MapPath(relpath));
                    return relpath;
                }
                catch (HttpException e)
                {
                    throw new ApplicationException("Cannot save uploaded file", e);
                }
            }
            return null;
        }
    

    然后,在控制器中我这样做:

    savedPath = SaveFile(Request.Files["logo"], somepath);
    

    【讨论】:

    • Request.Files 为空,但正在设置我的文件名字符串字段。我的 HTML 视图是:
    • 奇怪...返回值是什么?另外,为什么要为输入标签设置值 attr ?请注意,如果您重新运行表单(例如,如果表单无效并且用户必须更正某些内容),则不能重复使用它。
    • 已排序。缺少名称选项卡,视图中只有 id。 :)
    【解决方案2】:

    如有必要,您还可以通过 Request.Files 获取文件。

    【讨论】:

      【解决方案3】:

      在你的控制器动作中它应该出来

      Action(HttpPostedFileBase MyImageName) {
        etc;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-05-11
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 2014-11-04
        • 2022-01-11
        • 1970-01-01
        • 2011-04-16
        相关资源
        最近更新 更多