使用表单中的输入类型文件和c#HttpPostedFile上载文件

时间:2015-02-18 08:52:48

标签: c# html razor

我尝试使用输入类型文件上传文件,但我的代码无效。

变量" filePosted"保持空值。

我的代码:

HTML:

    <form method="post" name="gestionmembre" runat="server" enctype="multipart/form-data">
        @using (Html.BeginForm()){
                <label class="lmembre" for="nom">Nom:</label>@Html.TextBox("nom")<br />
                <label class="lmembre" for="prenom">Prénom:</label>@Html.TextBox("prenom", Request["Prenom"])<br />
                <label class="lmembre" for="mail">Mail:</label>@Html.TextBox("mail", Request["mail"])<br />
                <label class="lmembre" for="photo">Photo:</label><input id="phototelecharge" type="file" name="photo" value="Télécharger photo"/> <br /> 
                <div class="errorform">@Html.ValidationSummary()</div>
                <input id="ajoutmembre" type="submit" name="boutonmembre" value="Ajouter"/>
    }
    </form>

我不知道是否必须将此属性放在表单标记中(方法runat enctype)。

现在,在控制器中,在块中接收表单值,我把:

        else if (Request["boutonmembre"] == "Ajouter")
        {
            //Traitement de l'upload de l'image

            HttpPostedFile filePosted;
            filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];


            if (filePosted != null && filePosted.ContentLength > 0)
            {
                string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
                string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);

                // generating a random guid for a new file at server for the uploaded file
                string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
                // getting a valid server path to save
                string filePath = System.IO.Path.Combine(Server.MapPath("uploads"), newFile);

                if (fileNameApplication != String.Empty)
                {
                    filePosted.SaveAs(filePath);
                }
            }
        }

问题在于:

            filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];

变量fileposted为null。

在网页中,我从磁盘中选择一个文件,并在文本框中显示该文件的路径。

请帮帮我。 大卫

1 个答案:

答案 0 :(得分:1)

这是一个简单的例子

控制器

namespace stackoverflow.Controllers
{
    public class HomeController : Controller
    { 
       public ActionResult PostFile(HttpPostedFileBase myFile)
       {
            System.Diagnostics.Debugger.Break();
            return View();
       } 
    }
} 

查看

@using (Html.BeginForm("PostFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div id="postdata">
        <input type="file" name="myfile" id="myFile" />
        <input type="submit" value="submit" />
    </div>
}