Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Upload as Part of Form with Other Fields

I have an ASP.NET MVC website. I need a page where the user must enter several fields, including an image file.

I could find many, many references for uploading a file using MVC. But they don't upload the file as part of a form with other fields.

Ideally, fields and file will be sent to a single controller. Any tips?

like image 470
Jonathan Wood Avatar asked Jun 15 '13 21:06

Jonathan Wood


2 Answers

If you do not use third party libraries, try this:

Model

public class Strategy 
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public byte[] File { get; set; }

    }

View

 @model TEST.Model.Strategy
 @using (Html.BeginForm("Add", "Strategy", FormMethod.Post, new { @id = "frmStrategy", enctype = "multipart/form-data" }))
        {
            @Html.TextBoxFor(x => x.Name)
            <input id="templateFile" name="templateFile" type="file"  />
            @Html.HiddenFor(x => x.ID)

        }

Controller

[HttpPost]
        public ActionResult Add(Strategy model, HttpPostedFileBase templateFile)
        {


            if (templateFile != null && templateFile.ContentLength > 0)
            {
                try
                {
                    var fname = Path.GetFileName(templateFile.FileName);
                    using (MemoryStream ms = new MemoryStream())
                    {
                      templateFile.InputStream.CopyTo(ms);
                      byte[] array = ms.GetBuffer();
                      model.File = array;
                    }
                    ...
like image 185
Mate Avatar answered Nov 11 '22 00:11

Mate


You can use FineUploader. See Demo

Valums Uploader. It uses pure Javascript (uploads file using Iframe)

You might need to use a client plugin. Plupload is one possible choice. And here's an example of how you could integrate it in your MVC application. Another popular plugin which supports this functionality is Uploadify.

Asp.net mvc 3 file uploads using the fileapi

See Progress Demo 1, 2 & 3 at http://jquery.malsup.com/form/#file-upload

Ref: http://forums.asp.net/t/1897410.aspx/1?MVC4+File+Upload

like image 6
wakqasahmed Avatar answered Nov 10 '22 23:11

wakqasahmed