加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何从System.Web.HttpPostedFileBase转换为System.W

发布时间:2020-12-15 22:59:43 所属栏目:asp.Net 来源:网络整理
导读:在Scott Hanselman博客上尝试实现一个MVC文件上传 example.我遇到了这个示例代码的麻烦: foreach (string file in Request.Files){ HttpPostedFile hpf = Request.Files[file] as HttpPostedFile; if (hpf.ContentLength == 0) continue; string savedFileN
在Scott Hanselman博客上尝试实现一个MVC文件上传 example.我遇到了这个示例代码的麻烦:
foreach (string file in Request.Files)
{
   HttpPostedFile hpf = Request.Files[file] as HttpPostedFile;
   if (hpf.ContentLength == 0)
      continue;
   string savedFileName = Path.Combine(
      AppDomain.CurrentDomain.BaseDirectory,Path.GetFileName(hpf.FileName));
   hpf.SaveAs(savedFileName);
}

我把它转换成VB.NET:

For Each file As String In Request.Files
    Dim hpf As HttpPostedFile = TryCast(Request.Files(file),HttpPostedFile)
    If hpf.ContentLength = 0 Then
        Continue For
    End If
    Dim savedFileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,Path.GetFileName(hpf.FileName))
    hpf.SaveAs(savedFileName)
Next

但是我从编译器得到一个无效的转换异常:

Value of type 'System.Web.HttpPostedFileBase' cannot be converted to 'System.Web.HttpPostedFile'.

汉斯曼在2008-06-27发布了他的例子,我认为它在当时工作. MSDN没有任何类似的例子,所以给出了什么?

解决方法

只需使用它作为一个HttpPostedFileBase.该框架使用HttpPostedFileWrapper将HttpPostedFile转换为HttpPostedFileBase的对象. HttpPostedFile是那些难以单元测试的密封类之一.我怀疑在写了例子之后,他们应用了包装代码来提高在MVC框架中测试(使用HttpPostedFileBase)控制器的能力.控制器上的HttpContext,HttpRequest和HttpReponse属性已经完成了类似的操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读