首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将MVCRazorToPDF保存到位置或Blob,然后下载

将MVCRazorToPDF保存到位置或Blob,然后下载
EN

Stack Overflow用户
提问于 2014-09-30 21:15:25
回答 2查看 1.1K关注 0票数 1

下面是我的代码:

代码语言:javascript
复制
 public class ActionDownloadAttribute : ActionFilterAttribute 
 {
       public override void OnResultExecuted(ResultExecutedContext filterContext)
       {
             filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf");
             base.OnResultExecuted(filterContext);
       }
 }


[ActionDownload]
 public ActionResult GeneratePdf()
 {
       List<Comment> comments = null;
        using (var db = new CandidateEntities())
        {
            comments = db.Comments.ToList();
        }
        return new PdfActionResult("GeneratePdf", comments);
 }

上面的代码给出了我想(自动)在下载之前将其保存到特定路径或Blob的download.But文件。

在同样的情况下,有人能帮我吗?

EN

回答 2

Stack Overflow用户

发布于 2015-04-01 17:39:35

当我最初看着我的答案时,它并没有带来很多的value.So,我将尝试扩展。

非异步

首先,我有和你完全一样的控制器。然后,我使用restsharp调用该URL

代码语言:javascript
复制
        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个方法中的一个来上传byte[]或从流上传

代码语言:javascript
复制
 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;
    }
}

如果这有帮助,请告诉我。它适用于我的蓝色环境。我有一个网络作业生成这些文件,并将它们自动保存在blob上。

更新:异步

如果你想重写那些上传到Azure的异步方法,那么像下面这样的东西将使你能够进行以下调用:

代码语言:javascript
复制
    public async Task<ActionResult> asyncPDF()
    {
        return await AzureStorage._uploadToAzureBlob( ControllerContext.GeneratePdf(objModel, "VIEW_NAME") ) ;
    }

我将对该方法进行更详细的测试,以确认其行为。

欢迎评论:D

票数 1
EN

Stack Overflow用户

发布于 2020-10-09 06:15:14

请检查本例中的方法SaveToAppData:

https://github.com/andyhutch77/MvcRazorToPdf/blob/master/MvcRazorToPdfExample/Controllers/PdfController.cs

它使用来自ControllerContext的方法GeneratePdf来实现:

代码语言:javascript
复制
        byte[] pdfOutput = ControllerContext.GeneratePdf(model, "IndexWithAccessToDocumentAndWriter");
        string fullPath = Server.MapPath("~/App_Data/FreshlyMade.pdf");

        if (SysIO.File.Exists(fullPath))
        {
            SysIO.File.Delete(fullPath);
        }
        SysIO.File.WriteAllBytes(fullPath, pdfOutput);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26121823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档