我已经成功完成了上传位-将MP3文件上传到了我的SQL Server,但是在下载文件时需要帮助...。我使用以下代码上传MP3文件
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);
}
运行正常,这意味着文件存储在数据库中,现在如何使用实体框架从sql db下载MP3文件
要从MVC控制器下载MP3文件,请确保将MIME类型设置FileContentResult
为或(有关详细信息audio/mp3
,请参见http://filext.com/file-extension/MP3)。audio/mpeg3
audio/x-mpeg3
这是定义文件下载方案的简单控制器代码:
/*
* 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);
}
参考:使用Entity FrameWork从sql db查看和下载文件(对MP3扩展进行了调整)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句