簡體   English   中英

如何使用下載鏈接從 Azure Blob 存儲下載文件

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

我制作了一個 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”的訪問被拒絕。]

我認為問題在於我的應用程序沒有保存文件的路徑。 是否有可能獲得一個對話框,我可以在其中選擇保存路徑?

我想編寫一個類似的方法,以便您可以從視圖下載每個 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 方法的詳細信息。

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