How to download MP3 files with ASP.NET MVC 5 & Entity Framework

时间:2016-07-11 22:35:53

标签: c# asp.net asp.net-mvc entity-framework entity-framework-6

I have successfully done the upload bit - uploaded the MP3 files to my SQL Server, but I need help in downloading the files.... I use the following code to upload the MP3 file

public ActionResult Create([Bind(Include = "ID,Artist,Album")] TrackUpload trackUpload, HttpPostedFileBase upload)
{
    try
    {
        if (ModelState.IsValid)
        {
            if (upload != null && upload.ContentLength > 0)
            {
                var song = new File
                {
                    FileName = System.IO.Path.GetFileName(upload.FileName),
                    FileType = FileType.Songs,
                    ContentType = upload.ContentType
                };
                using (var reader = new System.IO.BinaryReader(upload.InputStream))
                {
                    song.Content = reader.ReadBytes(upload.ContentLength);
                }
                trackUpload.Files = new List<File> { song };
            }
            db.TrackUploads.Add(trackUpload);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }

    catch (RetryLimitExceededException /* dex */)
    {

        ModelState.AddModelError("", "Cant save changes.");
    }
    return View(trackUpload);
}

It is working fine which meaning the file stores in Database, Now how do i download the MP3 file from sql db using entity framework

1 个答案:

答案 0 :(得分:1)

要从MVC控制器下载MP3文件,请确保将MIME类型FileContentResult设置为audio/mp3audio/mpeg3audio/x-mpeg3(请参阅http://filext.com/file-extension/MP3有关详情)。

这是一个定义文件下载方案的简单控制器代码:

/*
 *  assume Id becomes file ID key to download
 *  this code provides simple download function by returning FileContentResult with proper MIME type
 */
public FileContentResult DownloadFile(int Id) 
{
    // assume FileContext is your file list DB context with FileName property (file name + extension, e.g. Sample.mp3)
    using (FileContext db = new FileContext())
    {
        var download = db.TrackUploads.Where(x => x.ID == Id).SingleOrDefault();
        if (download != null) 
        {
            // remove this line if you want file download on the same page
            Response.AddHeader("content-disposition", "inline; filename=" + download.FileName);
            return File(download.FileName, "audio/mp3");
        }
        else
        {
            return null;
        }
    }
}

<强>附录

要在下载之前从文件扩展名获取MIME类型,此代码部分可能有效:

if (download != null) 
{
    String mimeType = MimeMapping.GetMimeMapping(download.FileName);
    ...
    // other tasks
    ...
    return File(download.FileName, mimeType);
}

参考:view and download File from sql db using Entity FrameWork(调整MP3扩展名)