简体   繁体   English

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

[英]How to download files from Azure Blob Storage with a Download Link

I made an Azure Cloud Service, where you can upload and delete files to the cloud storage using Blobs.我制作了一个 Azure 云服务,您可以在其中使用 Blob 将文件上传和删除到云存储。 I wrote sucessfully a method where you can delete the uploaded blobs from the cloud service:我成功地写了一个方法,你可以从云服务中删除上传的 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";
    }
}

Here is also the code for View with HTML:这也是使用 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> 

Now I want to write a similiar method so you can download each blob from the View.现在我想编写一个类似的方法,以便您可以从视图中下载每个 blob。 I tried to write the methode using exactly the same code from the delete but instead of我尝试使用与删除中完全相同的代码编写方法,而不是

blob.delete();

now现在

blob.DownloadToFile(File);

This didn't work though.然而这并没有奏效。 Is there a possibility to change the delete method so it downloads the chosen blob instead of deleting it?是否有可能更改删除方法,以便下载所选的 blob 而不是删除它?


Added Info添加信息

Here is the code of DownloadToFile method:这是 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";
    }

The name is just the whole filename that is uploaded.该名称只是上传的整个文件名。 Filename is the data path.文件名是数据路径。

The Exception I get is:我得到的例外是:

UnauthorizedAccessException: The access to the path "C:\\Program Files\\IIS Express\\Eva Passwort.docx" is denied.] UnauthorizedAccessException: 对路径“C:\\Program Files\\IIS Express\\Eva Passwort.docx”的访问被拒绝。]

I think that the problem is that my application doesn't have a path to save the file.我认为问题在于我的应用程序没有保存文件的路径。 Is there a possibility to get a dialog where I can chose the path to save?是否有可能获得一个对话框,我可以在其中选择保存路径?

I want to write a similiar method so you can download each blob from the View.我想编写一个类似的方法,以便您可以从视图下载每个 blob。

It seems that you'd like to enable users to download the blob files, the following sample code work fine on my side, please refer to it.看来你想让用户下载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;
    }
}

Note: Detailed information about Controller.File Method .注意:有关Controller.File 方法的详细信息。

using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using OC3.Core.Model.Server;

namespace OC3.API.Controllers
{
    [Route("v1/desktop/[controller]")]
    [ApiController]
    [EnableCors("AllowOrigin")]
    public class DownloadController : Controller
    {
        private readonly IConfiguration _configuration;

        public DownloadController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        // code added by Ameer for downloading the attachment from shipments
        [HttpGet("Attachment")]
        public async Task<ActionResult> ActionResultAsync(string filepath)
        {
            ResponseMessage responseMessage = new ResponseMessage();

            responseMessage.resultType = "Download";

            try
            {
                if (!string.IsNullOrEmpty(filepath))
                {
                    responseMessage.totalCount = 1;

                    
                    string shareName = string.Empty;        

                    filepath = filepath.Replace("\\", "/");
                    string fileName = filepath.Split("//").Last();
                    if (filepath.Contains("//"))
                    {
                        //Gets the Folder path of the file.
                        shareName = filepath.Substring(0, filepath.LastIndexOf("//")).Replace("//", "/"); 
                    }
                    else
                    {
                        responseMessage.result = "File Path is null/incorrect";
                        return Ok(responseMessage);
                    }

                    string storageAccount_connectionString = _configuration["Download:StorageConnectionString"].ToString();
                    // get file share root reference
                    CloudFileClient client = CloudStorageAccount.Parse(storageAccount_connectionString).CreateCloudFileClient();
                    CloudFileShare share = client.GetShareReference(shareName);

                    // pass the file name here with extension
                    CloudFile cloudFile = share.GetRootDirectoryReference().GetFileReference(fileName);


                    var memoryStream = new MemoryStream();
                    await cloudFile.DownloadToStreamAsync(memoryStream);
                    responseMessage.result = "Success";

                    var contentType = "application/octet-stream";

                    using (var stream = new MemoryStream())
                    {
                        return File(memoryStream.GetBuffer(), contentType, fileName);
                    }
                }
                else
                {
                    responseMessage.result = "File Path is null/incorrect";
                }
            }
            catch (HttpRequestException ex)
            {
                if (ex.Message.Contains(StatusCodes.Status400BadRequest.ToString(CultureInfo.CurrentCulture)))
                {
                    responseMessage.result = ex.Message;
                    return StatusCode(StatusCodes.Status400BadRequest);
                }
            }
            catch (Exception ex)
            {
                // if file folder path or file is not available the exception will be caught here
                responseMessage.result = ex.Message;
                return Ok(responseMessage);
            }

            return Ok(responseMessage);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM