2011-08-04 60 views
2

此代碼應該使用MVC3控制器下載文件錯誤文件下載使用ASP MVC3

public FilePathResult GetFileFromDisk(String file) 
{ 
    String path = AppDomain.CurrentDomain.BaseDirectory + "AppData/"; 
    String contentType = "text/plain"; 
    return File(path+file, contentType, file); 
} 

查看部分:

@Html.ActionLink("Download", "GetFileFromDisk","Upload", new { file = "textfile" },null); 

但是,當我點擊鏈接我得到這個錯誤

找不到路徑'D:\ Project \ FileUploadDownload \ FileUploadDownload \ AppData \ textfile'的一部分。

[DirectoryNotFoundException:找不到路徑的一部分 'd:\項目\ FileUploadDownload \ FileUploadDownload \ AppData的\文本文件'。]

爲什麼FOLDERNAME在文件路徑重複?請提供一個解決方案...

回答

4

嘗試這樣的:

public ActionResult GetFileFromDisk(string file) 
{ 
    var appData = Server.MapPath("~/App_Data"); 
    var path = Path.Combine(appData, file); 
    path = Path.GetFullPath(path); 
    if (!path.StartsWith(appData)) 
    { 
     // Ensure that we are serving file only inside the App_Data folder 
     // and block requests outside like "../web.config" 
     throw new HttpException(403, "Forbidden"); 
    } 

    if (!System.IO.File.Exists(path)) 
    { 
     return HttpNotFound(); 
    } 

    var contentType = "text/plain"; 
    return File(path, contentType, Path.GetFileName(path)); 
} 
+0

您的解決方案是useful.Thanks很多.... – Binoy