当我最初查看我的答案时,它并没有真正带来很多价值。所以我会尝试扩展。
不异步
首先,我有与您完全相同的控制器。然后我使用 restsharp 调用那个 URL
var client = new RestClient("http://some.url.com");
var request = new RestRequest("mvc/GeneratePDF", Method.GET);
// execute the request
RestResponse response = (RestResponse)client.Execute(request);
// Zwracamy byte[] ktory jest naszym plikiem PDF
return response;
现在,如果您查看response.RawBytes,您可以在下面的方法中使用它来将字节数组直接上传到 Azure :)
我调用我的 2 种方法之一来上传字节 [] 或从流
public static class AzureStorage
{
/// <summary>
/// Metoda zajmujaca sie uploadem do Azure
/// </summary>
public static string _uploadToAzureBlob(byte[] arrPDF, string azureContainer, string filename)
{
// Retrieve connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConn"));
// Create blob client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(azureContainer);
// Create object blob
CloudBlockBlob blob = container.GetBlockBlobReference(filename);
// Upload
blob.UploadFromByteArray(arrPDF, 0, arrPDF.Length);
return blob.Uri.ToString();
}
/// <summary>
/// Metoda zajmujaca sie uploadem do Azure
/// </summary>
public static string _uploadToAzureBlob(Stream iostream, string azureContainer, string filename, bool ApplyReadPermissions = true)
{
// Retrieve connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConn"));
// Create blob client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(azureContainer);
// Create container if it does not exist
container.CreateIfNotExists();
// Create object blob
CloudBlockBlob blob = container.GetBlockBlobReference(filename);
iostream.Position = 0;//Move the pointer to the start of stream..
using (var fileStream = iostream)
{
blob.UploadFromStream(fileStream);
}
// Here we need to share the URL for reading the barcode! Otherwise we dont have access to it
if (ApplyReadPermissions)
{
var builder = new UriBuilder(blob.Uri);
builder.Query = blob.GetSharedAccessSignature(
new SharedAccessBlobPolicy
{
Permissions = SharedAccessBlobPermissions.Read,
SharedAccessStartTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(-5)),
SharedAccessExpiryTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(5))
}).TrimStart('?');
var x = builder.Uri.ToString();
return x;
}
return null;
}
}
让我知道这是否有帮助。它适用于我的天蓝色环境。我有一个 webjob 生成这些文件并将它们自动保存在 blob 上。
更新:异步
如果您将这些方法重写为上传到 Azure 为 Async,那么具有以下内容将使您能够执行以下调用:
public async Task<ActionResult> asyncPDF()
{
return await AzureStorage._uploadToAzureBlob( ControllerContext.GeneratePdf(objModel, "VIEW_NAME") ) ;
}
我将更详细地测试该方法以确认其行为。
非常欢迎评论:D