如何使用asp.mvc3中的fileupload控件将图像上传到服务器文件夹

时间:2011-04-21 06:35:20

标签: c# asp.net-mvc

当我使用asp.mvc3中的文件上传控件上传图像时,您能告诉我如何将图像保存到服务器路径图像文件夹中。请帮助我...

1 个答案:

答案 0 :(得分:2)

查看:

<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    { %>
        <div class="uploadfiles">
            <p><input type="file" name="files" /></p>
        </div>

        <a href="#add" id="additem">Add files</a><br />
        <input type="submit" value="Yes" />
<% } %>

<script type="text/javascript">
    $('#additem').live('click', function () {
        $('.uploadfiles').append($("<p><input type='file' name='files' /></p>"));
    });
</script>

控制器:

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(FormCollection[] form)
{
    for (int fileIndex = 0; fileIndex < Request.Files.Count; fileIndex++)
    {
        //let upload file to App_Data folder
        Request.Files[fileIndex].SaveAs(Server.MapPath("/App_Data/" + Request.Files[fileIndex].FileName));
    }
    return View();
}

这取决于文本框的名称,例如,如果View中有输入,请执行以下操作:

<input name="yourname" type="text" />

然后你可以在Controller使用中获得值:

var textBoxValue = formCollection["yourname"].ToString()