0

I am trying to enable visitors to upload images via my MVC website. The plan is for the user to upload the images and then in another action in the controller, fetch all of the images and display them.

My model has this field:

public virtual byte[] FileData{ get; set; }

And my database table has this column:

FileData varbinary

In my view I have the following:

<div class="form-group">
    @Html.LabelFor(model => model.FileData, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
            @Html.TextBoxFor(model => model.FileData, new { type = "file" })
            @Html.ValidationMessageFor(model => model.FileData)
    </div>
</div>

When I submit the form I get this error:

System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

My questions are:

Is the database table data type for the FileData column correct?

Is the model type for the FileData field correct?

What is the cause of the exception?

andrewb
  • 2,995
  • 7
  • 54
  • 95
  • There's an [answer here](http://stackoverflow.com/questions/15106190/uploading-files-into-database-with-asp-net-mvc). As for your exception: what is the source of the exception? What does the full stack trace look like? – Jasen Feb 01 '17 at 02:14
  • 1
    Use a view model with a property `HttpPosedFileBase File` to bind to - `@Html.TextBoxFor(m => m.File, new { type = "file })` and read the input stream into your data model's `byte[] FileData` property. –  Feb 01 '17 at 02:51

2 Answers2

0

I usually use HTML input of file type instead of the razor helper.

 <input type="file" id="imageInput" name="imageInput" value="" multiple="multiple" />

THen in the post action method, your action needs to mentioned

<form enctype="multipart/form-data" action="/controller/SaveImage" method="post">

The controller action should accept the file we are sending like this:

public ActionResult SaveImage(HttpPostedFileBase imageInput)
Arathy T N
  • 306
  • 3
  • 13
0

You can add it to your model:

public HttpPostedFileBase FileData{ get; set; }

And then in the view use it like that:

 @Html.TextBoxFor(model => model.FileData, new { type = "file" })
Victor Leontyev
  • 8,488
  • 2
  • 16
  • 36