How to allow File Downloads in MVC4 using VB.NET
We are using an ActionResult instead of FileResult.
Function download(id as Integer) As ActionResult
The reason is that if use the FileResult and your file does not exist then it will show a blank page, instead of this
we are using an ActionResult which is more versatile.
We can return the actual FileResult if the file exists
and in case of an error we can return a View (if we used a FileResult
Function download(id as Integer) As ActionResult
‘ In this example we are using the id to pick up the actual file from a model
Dim SoundFile as SoundFile = db.SoundFiles.Find(id)
Dim path As String = Server.MapPath(“~/myLocation/” & SoundFile.MP3File)
‘get file object as FileInfo
Dim fileinfo As System.IO.FileInfo = New System.IO.FileInfo(path)‘– if the file exists on the server
If fileinfo.Exists Then
rep.IncrementDownloadCount(id) ‘This is my routine to count the downloads, you will not need it
Return File(path, “application/octet-stream”, fileinfo.Name)
Else
Return View(“Error”)
End IfEnd Function