Loading mvc c # file as byte array

I need to upload files and other data in one form file UploadFile.cshtml

I have a base class that is an mvc action input to a home controller.

My base class, mvc action method and cshtml part with Razor script are below

I need to get a file as a byte array in a mvc action when submitting a UploadFile.cshtml form

My base class

public class FileUpload
{
  public string Name {get;set;}
  public int Age {get;set;}
  public byte[] Photo {get;set;}
}

      

MyMVCAction

[HttpPost]
public void UploadFile(FileUploadobj)
{
  FileUploaddata=obj;
}

      

Mycshtmlform

@modelMVC.Models.FileUpload
@using(Html.BeginForm("UploadFile","Home",FormMethod.Post))
{

<fieldset>
<legend>File Upload</legend>

<div class="editor-label">
@Html.LabelFor(model=>model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model=>model.Name)
</div>

<div class="editor-label">
@Html.LabelFor(model=>model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model=>model.Age)
</div>
<div class="editor-label">
@Html.Label("UploadPhoto");
</div>
<div class="editor-field">
<input type="file" id="photo" name="photo"/>
</div>
<p>
<input type="submit" value="Create"/>
</p>

</fieldset>

}

      

+3


source to share


1 answer


I think it's better to achieve it like this:

[HttpPost]
public ActionResult UploadFile(FileUpload obj) 
{
    using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
    {
       obj.Photo = binaryReader.ReadBytes(Request.Files[0].ContentLength);
    }  

    //return some action result e.g. return new HttpStatusCodeResult(HttpStatusCode.OK);
}

      



Hope this helps.

+1


source







All Articles