【问题标题】:Downloading byte[] of generated pdf using nodeservices in Asp.net Core 1.1在 Asp.net Core 1.1 中使用 nodeservices 下载生成的 pdf 的字节 []
【发布时间】:2018-03-14 22:33:01
【问题描述】:

我正在尝试下载 nodeServices 生成的字节数组形式的 pdf 文件。这是我的原始代码:

[HttpGet]
[Route("[action]/{appId}")]
public async Task<IActionResult> Pdf(Guid appId, [FromServices] INodeServices nodeServices)
{
    // generateHtml(appId) is a function where my model is converted to html.
    // then nodeservices will generate the pdf for me as byte[].
    var result = await nodeServices.InvokeAsync<byte[]>("./pdf", 
            await generateHtml(appId));
    HttpContext.Response.ContentType = "application/pdf";
    HttpContext.Response.Headers.Add("x-filename", "myFile.pdf");
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename");
    HttpContext.Response.Body.Write(result, 0, result.Length);
    return new ContentResult();
}

此代码运行良好,它将在浏览器中显示 pdf 文件,例如。 chrome,当我尝试下载它时,我得到“失败,网络错误”。

我在这里和那里搜索过,我看到了一些返回 File 的建议:

return File(result, "application/pdf");

这也不起作用,另一件事是添加“Content-Disposition”标题:

HttpContext.Response.Headers.Add("Content-Disposition", string.Format("inline;filename={0}", "myFile.pdf"));

其他人建议使用FileStreamResult,也不好。 我意识到问题可能与我生成的文件(字节 [])没有自己的路径或链接有关,所以我将字节保存到我的服务器,然后通过它的路径再次获取文件,然后到内存流,最后返回一个包含内存流的文件:

var result = await nodeServices.InvokeAsync<byte[]>("./pdf", await generateHtml(appId));
var tempfilepath = Path.Combine(_environment.WebRootPath, $"temp/{appId}.pdf");

System.IO.File.WriteAllBytes(tempfilepath, result);

var memory = new MemoryStream();
using (var stream = new FileStream(tempfilepath, FileMode.Open))
{
    await stream.CopyToAsync(memory);
}
memory.Position = 0;

return File(memory, "application/pdf", Path.GetFileName(tempfilepath));

哪个有效!它在浏览器中显示了文件,我可以下载它,但是,我不想将任何文件存储在我的服务器上,我的问题是,我不能直接下载文件而不需要存储它吗?

【问题讨论】:

    标签: c# pdf asp.net-core download asp.net-core-1.1


    【解决方案1】:

    您仍然可以返回 FileContentResult 而无需将字节数组转换为流。有一个overload of the File() methodfileContents 作为字节数组,将contentType 作为字符串。

    所以你可以重构为:

    public async Task<IActionResult> Pdf(Guid appId, [FromServices] INodeServices nodeServices)
    {
        var result = await nodeServices.InvokeAsync<byte[]>("./pdf", 
                await generateHtml(appId));
    
        return File(result, "application/pdf","myFile.pdf");
    }
    

    【讨论】:

    • 非常感谢!!我知道这种超载,我什至按照我在问题中解释的那样尝试了它,但它以前对我不起作用,无论如何我尝试了你的,结果证明它有效!!,所以我及时回去查看问题,那就是我没有在我的原始代码中注释掉HttpContext.Response.Con.. 行!这使文件无法下载。所以再次感谢你
    • 我的荣幸。真高兴你做到了。我完全错过了你说你试过return File(result, "application/pdf");...的问题部分:-/
    • 我很高兴你错过了它;)
    猜你喜欢
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2016-01-13
    • 1970-01-01
    • 2015-11-15
    • 2020-12-01
    相关资源
    最近更新 更多