我們在前一篇「
單一檔案與多檔案上傳及下載管理」有一段下載檔案的程式碼,如下:
01 | Function Download(id As Integer ) As ActionResult |
02 | Using db As New FilesEntities |
05 | Dim getfile = (From f In db.FileDown Where f.FileId = id Select f).FirstOrDefault() |
07 | If getfile.FileName IsNot Nothing Then |
08 | Dim FilePath As String = Server.MapPath( "~/Files/" & getfile.FileName) |
11 | If System.IO.File.Exists(FilePath) Then |
12 | Return File(FilePath, getfile.FileType, getfile.FileName) |
16 | Return Content( "<span style=" color: red; ">無法下載檔案!</span>" ) |
20 | Return RedirectToAction( "Index" ) |
一般而言,id 會是主鍵(PK),那如果我不想使用主鍵可不可以,也是可以,你只需要把LINQ那段語法修改一下即可,例如,我想使用檔案名稱來下載:
2 | Function DownloadByName(name As String ) As ActionResult |
3 | Dim getfile = (From f In db.FileDown Where f.FileName = name Select f).FirstOrDefault() |
不過像id, name 這種都很好猜,我可以手動輸入就可以把檔案下載回來。如果是這樣,那我們還可以使用GUID來讓使用者下載。
2 | Function DownloadByGuid(guid As Guid) As ActionResult |
3 | Dim getfile = (From f In db.FileDown Where f.rowguid= guid Select f).FirstOrDefault() |
另外,為確保傳入為Guid,再加強一下程式:
1 | Function DownloadByGuid(guid As String ) As ActionResult |
2 | Dim parseGuid As Guid = System.Guid.Parse(guid) |
3 | Dim getfile = (From f In db.FileDown Where f.rowguid= guid Select f).FirstOrDefault() |
經過 Guid.Parse() 的好處是,我可以使用Try ... Catch 直接進行錯誤處理。最後程式修改為:
01 | Function DownloadByGuid(guid As String ) As ActionResult |
03 | Dim parseGuid As Guid = System.Guid.Parse(guid) |
04 | Dim getfile = (From f In db.FileDown Where f.rowguid= guid Select f).FirstOrDefault() |
06 | If getfile.FileName IsNot Nothing Then |
07 | Dim FilePath As String = Server.MapPath( "~/Files/" & getfile.FileName) |
10 | If System.IO.File.Exists(FilePath) Then |
11 | Return File(FilePath, getfile.FileContentType, getfile.FileName) |
14 | Catch ex As ArgumentNullException |
15 | ViewBag.Message = ex.Message |
16 | Catch ex As FormatException |
17 | ViewBag.Message = ex.Message |
19 | ViewBag.Message = ex.Message |
22 | Return RedirectToAction( "Index" ) |
下載網址會是這樣:「http://localhost:15454/File/DownloadByGuid?guid=aeb238f8-d339-4997-bd9b-111c60906a15」,先把guid當成String,然後System.Guid.Parse(guid) 轉換為 Guid型別,成功才進行 LINQ 查詢,有資料就下載。
沒有留言:
張貼留言
感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。