Min*_*uoc 4 html c# azure-storage-blobs azure-cloud-services
我制作了一个 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";
}
}
Run Code Online (Sandbox Code Playgroud)
这也是使用 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>
Run Code Online (Sandbox Code Playgroud)
现在我想编写一个类似的方法,以便您可以从视图中下载每个 blob。我尝试使用与删除中完全相同的代码编写方法,而不是
blob.delete();
Run Code Online (Sandbox Code Playgroud)
现在
blob.DownloadToFile(File);
Run Code Online (Sandbox Code Playgroud)
然而这并没有奏效。是否有可能更改删除方法,以便下载所选的 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";
}
Run Code Online (Sandbox Code Playgroud)
该名称只是上传的整个文件名。文件名是数据路径。
我得到的例外是:
UnauthorizedAccessException: 对路径“C:\Program Files\IIS Express\Eva Passwort.docx”的访问被拒绝。]
我认为问题在于我的应用程序没有保存文件的路径。是否有可能获得一个对话框,我可以在其中选择保存路径?
我想编写一个类似的方法,以便您可以从视图下载每个 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;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:有关Controller.File 方法的详细信息。
| 归档时间: |
|
| 查看次数: |
30170 次 |
| 最近记录: |