我制作了一个 Azure 云服务,您可以在其中使用 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>
现在我想写一个类似的方法,这样你就可以从视图中下载每个 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";
}
该名称只是上传的整个文件名。文件名是数据路径。
我得到的例外是:
UnauthorizedAccessException:访问路径“C:\Program Files\IIS Express\Eva Passwort.docx”被拒绝。]
我认为问题是我的应用程序没有保存文件的路径。是否有可能获得一个对话框,我可以在其中选择保存路径?
原文由 Minh Anh Le Quoc 发布,翻译遵循 CC BY-SA 4.0 许可协议
看来你想让用户能够下载blob文件,下面的示例代码在我这边工作正常,请参考。
注意:有关 Controller.File Method 的详细信息。