Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Upload ASP.NET MVC

Basically what I have at the moment is a ASP.NET MVC project made database first the tables take alpha numeric input but I think it would be pretty nifty to have a file upload so I can insert a picture into the database so I created a table in SQL server with an ID field and an image field with the data type image.

When i add this model and create my controller and views based on that model it doesn't create the label or editor for this field, I used DataAnnotations to give it the DataType upload but I can't find a way of actually uploading the file I tried this which works for normal input but nothing shows up is there a way of having a @HTML.FileUploadFor(model => model.Vehicle) or something along those lines.

This is what I've tried

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

This is my model

public partial class VehicleImage
{
    public int Vehicle_ID { get; set; }
    [DataType(DataType.Upload)]
    public byte[] Vehicle { get; set; }
}
like image 898
Crouch Avatar asked Nov 28 '25 18:11

Crouch


2 Answers

There are many approaches to this.

I usually use a jquery plugin called Uploadify.

Have a look at this post - https://stackoverflow.com/a/17520062/1581026

Another way is just by adding the following in your view inside your form:

<input type="file" name="Picture" />

Your form element needs to look like the following:

 @using ( Html.BeginForm( "ACTION", "CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))

And then on your model that is getting passed to your POST Action you can add a attribute:

public HttpPostedFileBase Picture {get; set; }

Or you can also just add it as a parameter in your POST Action:

[HttpPost]
Public ActionResult SomeAction(HttpPostedFileBase Picture, .....)
like image 192
Jeandre Pentz Avatar answered Nov 30 '25 09:11

Jeandre Pentz


There isn't a standard control or helper for files as far as I know. However here is a nice tutorial to achieve what you want.

http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

Furthermore, if you really want this functionality, you can write an html helper yourself.

  1. by writing an extensionmethod to the HtmlHelper object
  2. By declaring a code block in your view eg:

@helper MyHelper(string id){ <input type="file" id="@id" /> }

like image 39
Yoeri Avatar answered Nov 30 '25 10:11

Yoeri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!