csharp 通过.net WebAPI将Azure存储专用容器blob下载/流式传输到AngularJS
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 通过.net WebAPI将Azure存储专用容器blob下载/流式传输到AngularJS相关的知识,希望对你有一定的参考价值。
using System;
using System.Configuration;
using System.IO;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
namespace MyApp.Providers
{
public class AzureProvider
{
public async Task<AzureBlobModel> GetAzureBlob(string containerName, string fileName)
{
var cloudBlockBlob = ResolveCloudBlockBlob(containerName, fileName);
var stream = await cloudBlockBlob.OpenReadAsync();
var blob = new AzureBlobModel()
{
FileName = fileName,
FileSize = cloudBlockBlob.Properties.Length,
Stream = stream,
ContentType = cloudBlockBlob.Properties.ContentType
};
return blob;
}
public async Task<string> UploadStreamToAzure(string containerName, string fileName, MemoryStream stream)
{
var blockBlob = ResolveCloudBlockBlob(containerName, fileName);
await blockBlob.UploadFromStreamAsync(stream);
return fileName;
}
public CloudBlockBlob ResolveCloudBlockBlob(string containerName, string fileName)
{
var container = ResolveCloudBlobContainer(containerName);
var blockBlob = container.GetBlockBlobReference(fileName);
return blockBlob;
}
public CloudBlobContainer ResolveCloudBlobContainer(string containerName)
{
var storageAccount = GetCloudStorageAccount();
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(containerName);
return container;
}
private CloudStorageAccount GetCloudStorageAccount()
{
return CloudStorageAccount.Parse(ResolveAzureStorageConnectionString());
}
public string ResolveAzureStorageConnectionString()
{
var accountName = ConfigurationManager.AppSettings["Azure.Storage.AccountName"]; // Get account name from web.config
var accessKey = ConfigurationManager.AppSettings["Azure.Storage.PrimaryAccessKey"]; // Get primary access key from web.config
return String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountName, accessKey);
}
}
}
(function () {
"use strict";
angular
.module("MyApp.Common")
.service("AzureBlobDownloadService", AzureBlobDownloadService);
AzureBlobDownloadService.$inject = ["$http", "$log"];
function AzureBlobDownloadService($http, $log) {
// Example call from an angular controller (AzureBlobDownloadService obviously needs to be injected):
// AzureBlobDownloadService.getBlob("/api/reports/sampleReport", { fileName: "someFileName" });
// NOTE: you should set the fileName through angular $http params instead of directly
// putting it into the url to avoid having problems with the dot (".") character ž
// in the url of your WebAPI call
this.getBlob = function (url, params) {
return $http.get(url, {
cache: false,
responseType: "arraybuffer",
headers: {
"Content-Type": "application/octet-stream; charset=utf-8"
},
params: params
}).success(function (data, status, headers) {
var octetStreamMime = "application/octet-stream";
headers = headers();
var fileName = !!headers["x-filename"] ? decodeURIComponent(escape(headers["x-filename"])) : "download.pdf";
var contentType = headers["content-type"] || octetStreamMime;
try {
var blob = new Blob([data], { type: contentType });
saveAs(blob, fileName);
} catch (ex) {
$log.error("Simulated download is not supported by your browser.");
$log.error(ex);
}
});
}
}
})();
using System.Web.Http;
using System.Threading.Tasks;
namespace MyApp.Controllers.API
{
[RoutePrefix("api/reports")]
public class ReportsController : BaseApiController
{
private AzureProvider _azureProvider;
public ReportsController()
{
_azureProvider = new AzureProvider();
}
[Route("sampleReport/{fileName}")]
public async Task<IHttpActionResult> GetSampleReport(string fileName)
{
var containerName = "democontainer";
var report = await _azureProvider.GetAzureBlob(containerName, fileName);
return AzureBlobOk(report);
}
}
}
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using MyApp.Models;
namespace MyApp.Infrastructure
{
public class BaseApiController : ApiController
{
/// <summary>
/// Returns HTTP status 200 (OK) when user tries to fetch private Azure blob through the backend/WebAPI.
/// </summary>
/// <param name="azureBlob">Azure Blob Model.</param>
/// <returns>Action result.</returns>
protected IHttpActionResult AzureBlobOk(AzureBlobModel azureBlob)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(azureBlob.Stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue(azureBlob.ContentType);
response.Content.Headers.Add("x-filename", azureBlob.FileName);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = azureBlob.FileName;
response.Content.Headers.ContentDisposition.Size = azureBlob.FileSize;
return ResponseMessage(response);
}
}
}
using System.IO;
namespace MyApp.Models
{
public class AzureBlobModel
{
public string FileName { get; set; }
public long? FileSize { get; set; }
public Stream Stream { get; set; }
public string ContentType { get; set; }
}
}
以上是关于csharp 通过.net WebAPI将Azure存储专用容器blob下载/流式传输到AngularJS的主要内容,如果未能解决你的问题,请参考以下文章
csharp Topshelf + OWIN自主机+ ASP.NET WebAPI + Ninject
csharp 从ASP.NET WebAPI控制器以camelCase格式返回JSON数据。
csharp 对于asp.net WebAPI客户端。启用cookie并以任何方式信任HTTPS认证。
java 通过httpclient调用https 的webapi