如何使用下载链接从Azure Blob存储下载文件

时间:2017-08-01 16:13:54

标签: c# html azure-storage-blobs azure-cloud-services

我制作了一个Azure Cloud Service,您可以使用Blob将文件上传和删除到云存储。我成功地写了一个方法,你可以从云服务中删除上传的blob:

 public string DeleteImage(string Name)
    {
        Uri uri = new Uri(Name);
        string filename = System.IO.Path.GetFileName(uri.LocalPath);

        CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer();
        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);

        blob.Delete();

        return "File Deleted";
    }
}

以下是使用HTML查看的代码:

@{
ViewBag.Title = "Upload";
}

<h2>Upload Image</h2>

<p>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = 
"multipart/form-data" }))
{
    <input type="file" name="image"/>
    <input type="submit" value="upload" />
}

</p>

<ul style="list-style-position:Outside;padding:0;">
@foreach (var item in Model)
{
<li>
    <img src="@item" alt="image here" width="100" height="100" />
    <a id="@item" href="#" onclick="deleteImage ('@item');">Delete</a>

</li>
}
</ul>

<script>
function deleteImage(item) {
    var url = "/Home/DeleteImage";
    $.post(url, { Name: item }, function (data){
        window.location.href = "/Home/Upload";
    });
}

</script> 

现在我想编写一个类似的方法,以便您可以从View中下载每个blob。我尝试使用与删除完全相同的代码来编写方法,而不是

blob.delete();

现在

blob.DownloadToFile(File);

但这不起作用。是否有可能更改删除方法,以便下载所选的blob而不是删除它?

添加了信息

以下是DownloadToFile方法的代码:

[HttpPost]
    public string DownloadImage(string Name)
    {
        Uri uri = new Uri(Name);
        string filename = System.IO.Path.GetFileName(uri.LocalPath);

        CloudBlobContainer blobContainer = 
_blobStorageService.GetCloudBlobContainer();
        CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);

        blob.DownloadToFile(filename, System.IO.FileMode.Create);


        return "File Downloaded";
    }

名称只是上传的整个文件名。 Filename是数据路径。

我得到的例外是:

UnauthorizedAccessException:拒绝访问路径“C:\ Program Files \ IIS Express \ Eva Passwort.docx”。]

我认为问题在于我的应用程序没有保存文件的路径。是否有可能获得一个对话框,我可以选择保存路径?

2 个答案:

答案 0 :(得分:1)

  

我想编写一个类似的方法,以便您可以从View中下载每个blob。

看来你想让用户下载blob文件,以下示例代码在我这边工作正常,请参考它。

public ActionResult DownloadImage()
{
    try
    {
        var filename = "xxx.PNG";
        var storageAccount = CloudStorageAccount.Parse("{connection_string}");
        var blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
        CloudBlockBlob blob = container.GetBlockBlobReference(filename);

        Stream blobStream = blob.OpenRead();

        return File(blobStream, blob.Properties.ContentType, filename);

    }
    catch (Exception)
    {
        //download failed 
        //handle exception
        throw;
    }
}

注意:有关Controller.File Method的详细信息。

答案 1 :(得分:0)

相关问题