我正在尝试下载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();
}
Run Code Online (Sandbox Code Playgroud)
此代码工作正常,它将在浏览器中显示pdf文件,例如.chrome,当我尝试下载它时,我得到"失败,网络错误".
我在这里和那里搜索过,我看到了一些返回文件的建议:
return File(result, "application/pdf");
Run Code Online (Sandbox Code Playgroud)
这也不起作用,另一件事是添加"Content-Disposition"标题:
HttpContext.Response.Headers.Add("Content-Disposition", string.Format("inline;filename={0}", "myFile.pdf"));
Run Code Online (Sandbox Code Playgroud)
其他人建议使用FileStreamResult,也没有好处.我意识到问题可能是关于我生成的文件(byte [])没有自己的路径或链接,所以我将字节保存到我的服务器,然后通过其路径再次获取文件,然后到内存流,最后返回一个包含内存流的文件:
var result = await nodeServices.InvokeAsync<byte[]>("./pdf", await generateHtml(appId));
var tempfilepath = Path.Combine(_environment.WebRootPath, …Run Code Online (Sandbox Code Playgroud)