4

I have to upload files and other data in a single submit of UploadFile.cshtml form

I have a base class which is the input of mvc action in home controller.

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

I have to get the file as byte array in the mvc action while submitting the 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>

}

1 Answer 1

2

I think better 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);
}

I hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.