C# 将字符串转换为HttpPostedFileBase

C# 将字符串转换为HttpPostedFileBase,c#,.net,asp.net-mvc,asp.net-mvc-3,file,C#,.net,Asp.net Mvc,Asp.net Mvc 3,File,我正在尝试使用MVC实现上传附件功能。我实际执行上传/保存附件的方法需要HttpPostedFileBase类型 public virtual string Upload(HttpPostedFileBase fileName) { //Code to upload/save attachment. } 我的问题是“文件名”作为字符串从UI传递。如何将字符串(文件路径名)转换为上载方法可以使用的内容 提前感谢。您不能只从UI传递字符串,您需要从输入类型=“file”上传文件。您必须

我正在尝试使用MVC实现上传附件功能。我实际执行上传/保存附件的方法需要HttpPostedFileBase类型

public virtual string Upload(HttpPostedFileBase fileName) 
{
     //Code to upload/save attachment.
}
我的问题是“文件名”作为字符串从UI传递。如何将字符串(文件路径名)转换为上载方法可以使用的内容


提前感谢。

您不能只从UI传递字符串,您需要从
输入类型=“file”
上传文件。您必须将
标记如下所示:

<form id="form_UploadFile" action="" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />
</form>

然后您将收到适当的
HttpPostedFileBase
对象

关于所有细节,您可以参考本手册

更新

使用ajax提交表单没有任何区别:

@使用(Ajax.BeginForm(“YourActionName”,null,新的AjaxOptions{UpdateTargetId=“YourTargetId”},新的{enctype=@“multipart/form data”}))
{
//你的意见在这里
}

您是否记得使用verbose
Html.BeginForm
方法

    @using (Html.BeginForm("Attach", "File", FormMethod.Post, new { enctype = "multipart/form-data" })) {
    }

重要的部分是
enctype=“multipart/form data”

正如其他人所提到的,您的表单应该如下所示:

<form id="form_UploadFile" action="" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />
</form>

我必须单独上传文件吗?我的意思是。。我正在使用类型=文件控件,但我正在等待用户单击“全部保存”按钮在其他字段上进行保存+同时从输入类型=文件控件上载附件…如果我正在使用ajax将值传递给控制器,该怎么办?