dhl: ASP.NET MVC1.0 的图片(文件)上传功能

知识点:System.Web(System.Web.Abstractions.dll) 的成员HttpPostedFileBase类

实例1单文件上传:

前台 :

<% using (Html.BeginForm("upload", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {%>
<input type="file" name="upfile" />
<input type ="submit" name ="upload" value ="上传" />
<%} %>

 

后台 :

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult upload(HttpPostedFileBase upfile) 
        { 
            if (upfile != null) 
            { 
                if (upfile.ContentLength > 0) 
                { 
                    upfile.SaveAs("d:\\7.jpg"); 
                } 
            }
        return Content(upfile.FileName); 
        } 

实例2多文件上传:

前台 :

<form action="<%=Url.Action("upload2") %>" enctype="multipart/form-data" method="post">
<input name="up1" type="file" />
<input name="up2" type="file" />
<input type="submit" />
</form>

后台:

public ActionResult upload2() 
        {
            try
            {
                HttpFileCollectionBase files = Request.Files;

                for (int iFile = 0; iFile < files.Count; iFile++)
                {
                    HttpPostedFileBase postedFile = files[iFile];
                    string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        postedFile.SaveAs("d:\\" + fileName);
                    }
                }
                TempData["info"] = "成功";
                return RedirectToAction("Warn"); 

            }
            catch (Exception ex)
            {
                TempData["info"] = "Err" + ex;
                return RedirectToAction("Warn"); 
            }

        }

 

注意:

多文件上传中,获得图片只能用:for - Requst.File[""]

而不能用以下foreach() 我也不知道为什么。(可能是HttpFileCollectionBase不是HttpPostedFileBase的集合,HttpFileCollectionBase..::.Item 屬性 是(String)类型,参考:http://msdn.microsoft.com/zh-tw/library/cc680819.aspx

HttpFileCollectionBase files = Request.Files;

foreach (HttpPostedFileBase fileBase in files)
                {
                    fileBase.SaveAs("d:\\a.jpg");
                }

所以用Foreach的话就这样写:

                foreach (string fileBase in files)
                {

                    HttpPostedFileBase postedFile = files[fileBase];
                    string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        postedFile.SaveAs("d:\\" + fileName);
                    }
                }

 

posted @ 2009-12-10 14:31  肚肚  阅读(558)  评论(0编辑  收藏  举报