2015-06-19 97 views
2

我當用戶點擊我的網頁文件使用此代碼,其中container我CloudBlobContainerAzure的Blob存儲下載文件,而不是在瀏覽器中打開

public void SaveFile(string blobPath, Stream stream) 
    { 
     stream.Seek(0, SeekOrigin.Begin); 
     CloudBlockBlob blockBlob = container.GetBlockBlobReference(virtualPath); 

     blockBlob.Properties.ContentDisposition = 
"attachment; filename=" + Path.GetFileName(virtualPath); 

     blockBlob.UploadFromStream(stream); 
    } 

然後將文件上傳到Azure的Blob存儲我試圖觸發一個下載,提示他們保存/打開文件。我通過調用一個返回一個重定向到blob URL的Action來做到這一點。

public ActionResult LoadFile(string path) 
    {  
     string url = StorageManager.GetBlobUrlFromName(path); 
     return Redirect(url); 
    } 

問題是這會打開瀏覽器中的文件,例如當我期待他們留在我的頁面上但開始下載文件時,用戶將被重定向離開我的網站並在瀏覽器中顯示一個.jpg文件。

+0

可能重複:http://stackoverflow.com/questions/20508788/do-i-need-content-type-application-octet-stream-for -file-download – adv12

+1

這歸結於響應中設置了HTTP標頭。你想要:'Content-Type:image/jpg'和 'Content-Disposition:attachment;文件名= 「picture.jpg」' – adv12

回答

0

一種方式來實現你想要的是一個MVC的行動來從Blob存儲影像並返回文件,即:

public ActionResult LoadFile(string path) 
{  
    byteArray imageBytes = ....get img from blob storage 
    return File(byteArray, "image/png", "filename.ext"); 
} 
1

你可能錯過的設置屬性後調用blockBlob.SetProperties()什麼。

在我的代碼,它看起來像這樣:

blob.CreateOrReplace(); 
blob.Properties.ContentType = "text/plain"; 
blob.Properties.ContentDisposition = "attachment; filename=" + Path.GetFileName(blobName); 
blob.SetProperties(); // !!! 
相關問題