2016-04-26 66 views
-1

直播網站,我有這樣的功能:無法下載文件到MVC 5

public ActionResult Download(string FileName) 
    { 

     if (FileName != null) 
     { 
      string filepath = AppDomain.CurrentDomain.BaseDirectory + "/uploads/" + FileName; 
      byte[] filedata = System.IO.File.ReadAllBytes(filepath); 
      string contentType = MimeMapping.GetMimeMapping(filepath); 

      var cd = new System.Net.Mime.ContentDisposition 
      { 
       FileName = FileName, 
       Inline = true, 
      }; 

      Response.AppendHeader("Content-Disposition", cd.ToString()); 

      return File(filedata, contentType); 
     } 
     return RedirectToAction("Index"); 
    } 

相同的代碼在本地服務器工作,但不是在活的服務器,任何人都可以告訴我原因嗎?

+0

首先我會看是'filepath' – jamiedanq

+0

你可以用這種方式來嘗試:刪除「string filepath = ...」行並更新「byte [] filedata = ...」行:byte [] filedata = System.IO.File.ReadAllBytes(Server.MapPath (「〜/ uploads /」+ FileName +「」)); – kkakkurt

+1

請閱讀[問]並解釋這是如何「無法正常工作」。 – CodeCaster

回答

0

這可能b不是你的答案,但你可以使用return File(path, System.Net.Mime.MediaTypeNames.Application.Octet, name); 將下載文件,寫整個事情在單行 ......(我用它在mvc4,它在真實生活的作品也..)

由於例如,

var audio_path = "/" + path.Substring(path.IndexOf("Content")); 
String audio_name = path.Substring(path.LastIndexOf("/") + 1); 
return File(audio_path, System.Net.Mime.MediaTypeNames.Application.Octet, audio_name); 
-1

您可以使用以下代碼下載文件:

#region Download File ==> 
     public ActionResult downloadfile(string Filename, string MIMEType) 
     { 
      try 
      { 
       string file_name = "/Files/EvidenceUploads/" + Filename; 
       string contentType = ""; 
       //Get the physical path to the file. 
       string FilePath = Server.MapPath(file_name); 

       string fileExt = Path.GetExtension(file_name); 

       contentType = MIMEType; 

       //Set the appropriate ContentType. 
       Response.ContentType = contentType; 
       Response.AppendHeader("content-disposition", "attachment; filename=" + (new FileInfo(file_name)).Name); 

       //Write the file directly to the HTTP content output stream. 
       Response.WriteFile(FilePath); 
       Response.End(); 
       return View(FilePath); 
      } 
      catch 
      { 
       Response.End(); 
       return View(); 
       //To Do 
      } 

     } 
     #endregion 
+0

它仍然給錯誤頁面,請檢查圖片上的錯誤http://s32.postimg.org/unacqjlz9/Screen_Shot_2016_04_26_at_7_44_24_PM.png –