TAGS :Viewed: 7 - Published at: a few seconds ago

[ HttpPostedFileBase returns Null MVC3 ]

I'm developing a project in C# with MVC4. Here my question:

I'm trying to convert a byte[] to HttpPostedFileBase, but it always returns Null (even if the byte[] contains data). Here the code I have:

public override bool IsValid(object value)        {               
HttpPostedFileBase file = value as HttpPostedFileBase

That code is part of my IsValid function where I'm validating if the uploaded image is Valid (less than 1MB, just 'jpg' or 'png', etc.). Thanks in advance.

Answer 1

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

Edit : method="post"



plz post your controller code else try this above

Answer 2

With Html helper class you can write it as follows

@using (Html.BeginForm("Create", "Company", FormMethod.Post, new { enctype = "multipart/form-data" }))
    <input type="file" name="LogoFileUp" id="LogoFileUp"></span>

and in Create Post Action you can get value as:

public ActionResult Create( HttpPostedFileBase LogoFileUp)
   // bla bla ...

Answer 3

In addition to Elvin's answer you can use a model where you can add dataanotations containing the extensions you want to allow: http://msdn.microsoft.com/en-us/library/ee256141%28VS.100%29.aspx

The Model: CompanyModel.cs

public class CompanyModel
    [Display(Name = "Logo")]
    [File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png" }, MaxContentLength = 1024 * 1024 * 30, ErrorMessage = "Invalid File")]
    public HttpPostedFileBase LogoFileUp{ get; set; }

    //you can add other properties if you like, for example companyname

The View

@model CompanyModel
@using (Html.BeginForm("Create", "Company", FormMethod.Post, new { enctype = "multipart/form-data" }))
    @Html.ValidationMessageFor(model => model.LogoFileUp)
    @Html.LabelFor(model => model.LogoFileUp)
    @Html.TextBoxFor(model => model.LogoFileUp, new { type = "file" })

The Action

public ActionResult Create(CompanyModel company)

    if (ModelState.IsValid)
        //save company ...
        return View(company)