2010-09-13 20 views
0

這裏是電話...這段代碼爲什麼會向瀏覽器發送0kb文件?

return new FileUriResult("application/octet-stream", a.AssetPath, null); 

[注意,我設置內容長度爲空,因爲我不知道它(文件在另一臺服務器上)

a.AssetPath是:「 http://http.cdnlayer.com/account名/文件夾/文件夾/文件夾/ asset.mp3"

(在這個例子中,但在我執行我可以直接瀏覽文件假的網址,但該連接方法是不工作)

這裏是實施...

public class FileUriResult : ActionResult 
    { 
     private string _contentType; 
     private string _fileUri; 
     private long? _fileLength; 

     public FileUriResult(string contentType, string fileUri, long? fileLength) 
     { 
      _contentType = contentType; 
      _fileUri = fileUri; 
      _fileLength = fileLength; 
     } 

     public override void ExecuteResult(ControllerContext context) 
     { 
      if (context == null) 
      { 
       throw new ArgumentNullException("context"); 
      } 

      HttpResponseBase response = context.HttpContext.Response; 

      response.ContentType = _contentType; 
      response.AddHeader("Content-Disposition", "attachment; filename=" + _fileUri); 
      if(_fileLength != null) 
       response.AddHeader("Content-Length", _fileLength.ToString()); 
     } 
    } 

文件被直接下載,就像我想(不受瀏覽器中打開),但它是不是文件,它只是一個具有相同名稱的0KB文件。

+0

我不知道MVC,但我的蜘蛛俠說你可能需要添加文件的內容到響應,否則它只是發送有關文件的信息,無文件本身(信息如文件名) – 2010-09-13 18:25:56

回答

1

您只能通過使用例如FileResult發送二進制數據來強制下載作爲附件。您不能以這種方式強制從URL下載文件。所有你告訴瀏覽器的是接下來的是一個附件,你給它的URL作爲保存它的名字。

您需要自己讀取文件,並將其寫入響應中作爲一系列字節。

+0

謝謝,這是有道理的,我總是期望太多的技術 – BigOmega 2010-09-13 18:43:02

相關問題