将文件读取到项目中无法正常工作的字节

问题描述 投票:0回答:1

我有一个奇怪的问题。我正在制作一个C#MVC应用程序,它生成PDF并通过下载按钮提供下载。

public ActionResult Download()
{
    string url = (string)TempData["url"];

    byte[] thePdf = System.IO.File.ReadAllBytes(url);

    return File(thePdf, "application/pdf");
}

突然之间,我无法使用byte[]File.ReadAllBytes()(或任何其他流)将PDF文件正确转换为MemoryStream

当我使用MemoryStream时,我在InvalidOperationExceptionReadTimeOut都得到了WriteTimeOut

我在一个新的C#MVC项目中实现了上面提到的代码,一切都运行良好。所以问题必须与我正在从事的项目有关。

c# asp.net-mvc
1个回答
0
投票

如果您的网址是远程网址,则应使用WebClient下载如下数据。

我试图重现你的代码,它的工作原理。

 public ActionResult Download()
        {
            string url = (string)TempData["url"];

            url = "http://www.iuh.edu.vn/Tuyensinh/QC/TomTatQuyCheThiTHPT2018.pdf";

            using (var client = new WebClient())
            {
                // read data
                byte[] thePdf = client.DownloadData(url);

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

            }

            //byte[] thePdf = System.IO.File.ReadAllBytes(url);

            //return File(thePdf, "application/pdf");
        }

在cshtml中:

<input type="button" value="Download" onclick="window.location.href='/YourController/Download'" />
© www.soinside.com 2019 - 2024. All rights reserved.