简体   繁体   中英

mvc c# file upload as byte array

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>

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM