File Upload ASP.NET MVC 3.0

后端 未结 21 999
无人共我
无人共我 2020-11-22 01:09

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

I want to

21条回答
  •  无人共我
    2020-11-22 01:54

    please pay attention this code for upload image only. I use HTMLHelper for upload image. in cshtml file put this code

    @using (Html.BeginForm("UploadImageAction", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm" }))
    {
        
    @Html.UploadFile("UploadImage")
    }

    then create a HTMLHelper for Upload tag

    public static class UploadHelper
    {
    public static MvcHtmlString UploadFile(this HtmlHelper helper, string name, object htmlAttributes = null)
    {
        TagBuilder input = new TagBuilder("input");
        input.Attributes.Add("type", "file");
        input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
        input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));
    
        if (htmlAttributes != null)
        {
            var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            input.MergeAttributes(attributes);
        }
    
        return new MvcHtmlString(input.ToString());
       }
    }
    

    and finally in Action Upload your file

            [AjaxOnly]
            [HttpPost]
            public ActionResult UploadImageAction(HttpPostedFileBase UploadImage)
            {
               string path = Server.MapPath("~") + "Files\\UploadImages\\" + UploadImage.FileName;
               System.Drawing.Image img = new Bitmap(UploadImage.InputStream);    
               img.Save(path);
    
               return View();
            }
    

提交回复
热议问题