首页 文章

Azure blob存储下载文件,而不是在浏览器中打开

提问于
浏览
2

我使用此代码将文件上载到Azure blob存储,其中 container 是我的CloudBlobContainer

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);
    }

然后当用户点击我的网页中的文件时,我试图触发下载,提示他们保存/打开文件 . 我这样做是通过调用一个返回重定向到blob URL的Action .

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

问题是这将打开浏览器中的文件,例如当用户希望它们留在我的页面上但开始下载文件时,用户将重定向远离我的网站并在浏览器中显示.jpg文件 .

2 回答

  • 1

    实现所需的一种方法是MVC操作从blob存储中获取图像并返回File,即:

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

    您可能错过的是在设置属性后调用 blockBlob.SetProperties() .

    在我的代码上它看起来像这样:

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

相关问题