[RESOLVED]Upload audio file and save to Database in ASP.NET MVC using Codefirst EF.

Hi,

I am a newbie!

Could anybody please help me in uploading audio file and saving it to sqlserver db in ASP.Net MVC using Codefirst EF.

Thanks for support!

Best Regards,

Hunaid.

www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

Hi,

Here an example. This example filter for picture only but you can modify to your audio file:

  1. This is on "Views" part, there is a special parameters on "@using"
    @model PersonEntity.Model.BusinessEntityPhotoSet
    
    @{
        ViewBag.Title = "UploadPrimePhoto";
    }
    
    <h2>UploadPrimePhoto</h2>
    
    @using (Html.BeginForm("UploadPrimePhoto", "Person", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <h4>BusinessEntityPhotoSet</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.PersonId)
    
            <div class="form-group">
                @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.File, new { type = "file" })
                    @Html.ValidationMessage("CustomError")
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.PrimaryPhoto, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.PrimaryPhoto)
                        @Html.ValidationMessageFor(model => model.PrimaryPhoto, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
  2. This part on COntroller. Here there is a filter to save on database or file folder on server you may also changed it to your requirement, another filter for file size you can remove if necessary:
     public ActionResult UploadPrimePhoto(int id)
            {
                BusinessEntityPhotoSet photo = new BusinessEntityPhotoSet();
                photo.PersonId = id;
                photo.PrimaryPhoto = false;
                return View(photo);
            }
    
            public ActionResult UploadPrimePhoto(BusinessEntityPhotoSet photo)
            {
                Person person = db.People.Find(photo.PersonId);
    
                photo.ModifiedDate = DateTime.Now;
                if (photo.File != null)
                {
                    if (photo.File.ContentLength > (2 * 1024 * 1024) && photo.File.ContentLength < 1)
                    {
                        ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                        return View(photo);
                    }
    
                    photo.ImageSize = photo.File.ContentLength;
                    photo.ImageSource = Guid.NewGuid() + Path.GetExtension(photo.File.FileName); // photo.File.FileName;
                    /** Photo dibawh 61KB disimpan di database, sisanya disimpan di folder, dengan nama NewGuid() **/
                    if (photo.File.ContentLength < 61676)
                    {
                        photo.Photo = ConvertFile.ImageToByte(photo.File);
                    }
                    else
                    {
                        photo.Photo = null;
                        var path = Path.Combine(Server.MapPath("~/images/normal"), photo.ImageSource);
                        photo.File.SaveAs(path);
                    }
                }
    
                if (ModelState.IsValid)
                {
                    bool primaryPhoto = photo.PrimaryPhoto == null ? false : Convert.ToBoolean(photo.PrimaryPhoto);
                    if (primaryPhoto)
                    {
                        person.ImageSource = photo.ImageSource;
                        db.Entry(person).State = EntityState.Modified;
                    }
                    db.BusinessEntityPhotoSets.Add(photo);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                return View(photo);
            }
  3. This is a helper. A filter here for .jpeg, .png, and .giff you can change it to audio file type:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web;
    using System.IO;
    
    namespace PersonEntity.Model
    {
        public static class ConvertFile
        {
            public static byte[] ImageToByte(HttpPostedFileBase imageFile)
            {
                if (imageFile == null) { return null; }
                return (imageFile.ContentType == "image/jpeg" || imageFile.ContentType == "image/gif" || imageFile.ContentType == "image/png") ? FileToByte(imageFile) : null;
            }
    
            public static byte[] FileToByte(HttpPostedFileBase file)
            {
                byte[] data = new byte[file.ContentLength];
                file.InputStream.Read(data, 0, file.ContentLength);
                return data;
            }
        }
    
        public static class Files
        {
            public static string UpLoad(IEnumerable<HttpPostedFileBase> files, string serverPath)
            {
                int count = 0;
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        if (file != null && file.ContentLength > 0)
                        {
                            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                            var path = Path.Combine(serverPath, fileName);
                            file.SaveAs(path);
                            count++;
                        }
                    }
                }
    
                return count == 0 ? "No files uploaded!" : "Successfully " + count + " file(s) uploaded!";
            }
        }
    }
  4.  You need to add a partial class on the model side. Please make sure that you must have the same NameSpace with the class. Need to put it on a separate folder but change the nameSpace to the model class:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web;
    
    namespace PersonEntity.Model
    {
        [MetadataType(typeof(BusinessEntityPhotoSetMetadata))]
        public partial class BusinessEntityPhotoSet
        {
            public HttpPostedFileBase File { get; set; }
        }
        public class BusinessEntityPhotoSetMetadata
        {
            [Display(Name = "Image File Name")]
            public string ImageSource { get; set; }
    
            [Display(Name = "Image Size")]
            public int ImageSize { get; set; }
        }
    }

Have fun

Hi itshunaid,

Thanks for your post.

I did a sample,you can refer to the following code snippet according to your requirement and modify it and then use it:

action:

  public ActionResult file()
        {
            return View();
        }
        [HttpPost]
        public ActionResult file(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
                try
                {

                    string path = Path.Combine(Server.MapPath("~/Content/files"), Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    ViewBag.Message = "File uploaded Successfully";
                }
                catch (Exception ex)
                {

                    ViewBag.Message = "Error:" + ex.Message.ToString();
                }
            else
            {
                ViewBag.Message = "You have not Specified a file";
            }
            return View();

        }

view:

@{
    ViewBag.Title = "file";
}

<h2>file</h2>
@using (Html.BeginForm("file", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" id="file" /><br />
    <input type="submit" value="Upload file" />
     <br />
    @ViewBag.Message
}

More information:

Asp.net MVC Upload audio files

Hope this can be helpful.

Best Regards,

Eileen

Hi jsiahaan,

Thank you so much for this wonderful work! Really appreciate your help.

Best Regards,

Hunaid Hussain.

Hi Eileen,

Thanks a lot for your great help. Really appreciate your effort!

Best Regards,

Hunaid Hussain.

Hi ignatandrei,

A very big thank you for your post. Appreciate your help!

Best Regards,

Hunaid Hussain.

Hi,

No problem, glad to hear it can help.

Hi,

Could you please also help me in display images on view from db?

Best Regards.

Hunaid Hussain.

Hi itshunaid,

Thanks for your post.

I suggest that you can reopen the case later.

Here is a sample,you can refer to the following code snippet:

table:

CREATE TABLE [dbo].[tblA]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [fname] NVARCHAR(50) NULL, 
    [lname] NVARCHAR(50) NULL, 
    [imageUrl] NVARCHAR(50) NULL
)
  • Creat an "Images" folder in Solution explorer.
  • Create an ADO.NET Entity Data Model (in this example is "Database1Entities") 
  • Home Controller: 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace test2.Controllers
    {
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
        return View();
    }
    
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
    
        if (file != null)
        {
            Database1Entities db = new Database1Entities();
            string ImageName = System.IO.Path.GetFileName(file.FileName);
            string physicalPath =Server.MapPath("~/images/"+ ImageName);
    
            // save image in folder
            file.SaveAs(physicalPath);
    
            //save new record in database
            tblA newRecord = new tblA();
            newRecord.fname = Request.Form["fname"];
            newRecord.lname = Request.Form["lname"];
            newRecord.imageUrl = ImageName;
            db.tblAs.Add(newRecord);
            db.SaveChanges();
    
        }
        //Display records
        return RedirectToAction("../home/Display/");
    }
    
    public ActionResult Display()
    {
        return View();
    }
    }
    }
  • Index View 

    @{
       ViewBag.Title = "Index";
    }
    
    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
    {
    <div>
    First name<br />
    @Html.TextBox("fname") <br />
    Last name<br />
    @Html.TextBox("lname") <br />
    Image<br />
    <input type="file" name="file" id="file" style="width: 100%;" /> <br />
    <input type="submit" value="Upload" class="submit" />
    </div>    
    }
  • Display View 

    @{
        ViewBag.Title = "Display";
    }
    
    @{
       test2.Database1Entities db = new test2.Database1Entities();
    }
    @using (Html.BeginForm())
    {
    <table border="1">
    <thead>
        <tr>
            <th>Image</th>
            <th>First name</th>
            <th>Last name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in db.tblAs)
        {
            <tr>
                <td><img src="~/images/@item.imageUrl" width="100" height="100" /></td>
                <td>@item.fname</td>
                <td>@item.lname</td>
            </tr>
        }
    </tbody>
    </table>
    }

Output:

/Home/ 

/home/Display/ 

More information:

http://forums.asp.net/t/1981336.aspx?Storing+Image+Url+in+Database

http://stackoverflow.com/questions/17499259/upload-a-picture-to-a-database-in-asp-mvc-4

Hope this can be helpful.

Best Regards,

Eileen

Leave a Reply