将字符串转换为HttpPostedFileBase

3

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

public virtual string Upload(HttpPostedFileBase fileName) 
{
     //Code to upload/save attachment.
}

我的问题是,UI界面传递的“fileName”是一个字符串。我该如何将这个字符串(文件路径名)转换成我的上传方法可以使用的内容?
提前致谢。
4个回答

4
正如其他人所提到的,你的表格应该看起来像这样:

<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发布内容,您可以使用jQuery serialize()来将formData序列化为要推送到控制器的数据。

$('#form_UploadFile').serialize();

3

你不能仅仅从UI中传递一个字符串,你需要从input type="file"上传文件。


我需要单独进行文件上传吗?我的意思是,我正在使用type=file控件,但我希望用户单击“保存所有”按钮时同时保存其他字段和上传来自input type=file控件的附件。 - ZVenue

2

您需要将<form>标签设置为以下格式:

<form action="" method="post" enctype="multipart/form-data">

然后您将收到正确的HttpPostedFileBase对象。

您可以参考这篇文章了解所有细节。

更新

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

@using (Ajax.BeginForm("YourActionName", null, new AjaxOptions { UpdateTargetId = "YourTargetId" }, new { enctype = @"multipart/form-data" }))
{
    //Your inputs here
}

如果我正在使用Ajax将值传递给控制器怎么办? - ZVenue

2

你是否记得使用详细的 Html.BeginForm 方法?

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

重要的部分是 enctype="multipart/form-data"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接