(上传文件)HttpPostedFile类和HttpPostedFileBase类

简单的文件上传代码如下:
Example(例子):

/Controllers/AdminController.cs

 [HttpGet]
        public ActionResult NewsAdd(string name)
        {//参考资料在QQ群:683782676
            //创建数据 查询出新闻的所有类型
            List<TopicModel> lt = tb.FindTopicAll(null);
            //将集合转换为下拉的列表
            SelectList sl = new SelectList(lt, "tid", "tname");
            //将下拉的列表传递给页面 IEnumerable 
            ViewBag.DropDownListDataSouces = sl.AsEnumerable();
            return View();
        }
        [HttpPost]
        public ActionResult NewsAdd(HttpPostedFileBase image, NewsModel news/*,string name*/)
        {
            //string outStr = string.Format("长度:{0},文件的类型:{1},文件的名称:{2}", image.ContentLength,                 image.ContentType, image.FileName);
            //Console.WriteLine(outStr);

            //1 设置服务器的保存地址
            string path = Server.MapPath("~/upload/");
            //2 更改你的文件的名称  
            string fileName = image.FileName.Substring(image.FileName.LastIndexOf("."));
            fileName = DateTime.Now.ToLongDateString() + "-" + new Random().Next() + fileName;

            //DateTime.Now.ToFileTimeUtc();

            //3 将文件放入到服务器的保存路径地址中
            path += fileName;
            //4 保存文件
            image.SaveAs(path);
            //5 得到文件的保存地址 并将文件保存地址放入到数据库中
            news.nfile = path;

            //保存数据
            NewsModel nm = new NewsModel()
            {
                nid = Guid.NewGuid(),
                tid = news.tid,
                title = news.title,
                author = news.author,
                summary = news.summary,
                ncontent = news.ncontent,
                nfile = news.nfile,
                ndate = DateTime.Now
            };
            if (nb.AddNews(nm) > 0)
            {
                return RedirectToAction("NewsAdmin");
            }
            else
            {
                Response.Write("<sctipt>alert('操作失败!!!');</script>");
                return View();
            }
        }

/Views/Admin/NewsAdd.cshtml

@model News.Model.NewsModel
@{
    ViewBag.Title = "NewsAdd";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<div id="main">
    <div id="opt_list">
        <ul>
            <li><a href="../newspages/news_add.jsp">添加新闻</a></li>
            <li><a href="../admin.jsp">编辑新闻</a></li>
            <li><a href="#">查找新闻</a></li>
            <li><a href="../newspages/topic_add.jsp">添加主题</a></li>
            <li><a href="#">编辑主题</a></li>
        </ul>
    </div>
    <div id="opt_area">
        <h1 id="opt_type"> 添加新闻: </h1>
        <form action="Admin/NewsAdd" method="post"></form>
        @using (Html.BeginForm("NewsAdd", "Admin",FormMethod.Post,new { enctype = "multipart/form-data" }))
        {
            <p>
                @Html.LabelFor(model => model.tid):&nbsp;
                @Html.DropDownList("tid", ViewBag.DropDownListDataSouces as IEnumerable<SelectListItem>, "请选择")
            </p>
            <p>
                @Html.LabelFor(model => model.title):&nbsp;@Html.TextBoxFor(model => model.title)
            </p>
            <p>
                @Html.LabelFor(model => model.author):&nbsp;@Html.TextBoxFor(model => model.author)
            </p>
            <p>
                @Html.LabelFor(model => model.summary):&nbsp;@Html.TextAreaFor(model => model.summary, new { cols = "40", rows = "3" })
            </p>
            <p>
                @Html.LabelFor(model => model.ncontent):&nbsp;@Html.TextAreaFor(model => model.ncontent, new { cols = "70", rows = "10" })
            </p>
            <p>
                @Html.LabelFor(model => model.nfile):&nbsp;
                <input name="image" type="file" class="opt_input" />
            </p>
            <input type="submit" value="提交" class="opt_sub" />
            <input type="reset" value="重置" class="opt_sub" />
        }    
    </div>
</div>



转:

当你看到的时候,你是不是已经爱上了它,如果你真的只看外表,那你就错了,不要太相信自己的眼睛,往往真像并不是你所看到的那么简单!请跟我一起来看看吧!

这次在项目中,就遇到了这个问题,刚开始我还天真的以为他们真的有关系,没有到都是假象的。

遇到的问题:“把图片上传到资源服务器”的一个上传问题,刚开始做的时候没考虑到,代码如下:

public bool UploadFTP(HttpPostedFileBase file, string strFileType, int iFileLength, int Width, int Height, string Path, ref string strInfo)
{
   ............. //     
}

本以为这样就已经是通用的了,当我直接传HttpPostedFile 对象的时候报错了。答案是 HttpPostedFileHttpPostedFileBase不存在关系。

所以我只好,到晚上去找,去查,终于找到了一个好的解决方案,其实它们还是可以通过一个桥梁 HttpPostedFileWrapper 类来转化,HttpPostedFileWrapper : HttpPostedFileBaseHttpPostedFileWrapper 的代码如下:

public class HttpPostedFileWrapper : HttpPostedFileBase
{
        // 摘要:
        //     初始化 System.Web.HttpPostedFileWrapper 类的新实例。
        //
        // 参数:
        //   httpPostedFile:
        //     通过此包装类可访问的对象。
        //
        // 异常:
        //   System.ArgumentNullException:
        //     httpApplicationState 为 null。
        public HttpPostedFileWrapper(HttpPostedFile httpPostedFile);
}

最后解决方案如下:
public bool UploadFTP(HttpPostedFile file, string strFileType, int iFileLength, int Width, int Height, string Path, ref string strInfo)
{//参考资料在QQ群:683782676
HttpPostedFileBase hpfb = new HttpPostedFileWrapper(file) as HttpPostedFileBase;
return UploadFTP(hpfb, strFileType, iFileLength, Width, Height, Path, ref strInfo);
}


版权声明:本文为qq_43023809原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。