【问题标题】:OutputStream is not available when a custom TextWriter is used使用自定义 TextWriter 时,OutputStream 不可用
【发布时间】:2010-05-05 21:21:16
【问题描述】:

这是我将 pdf 转换为 png 图像的函数,它会引发错误 这一行——> stream.WriteTo(Response.OutputStream);有什么不对吗??

protected void CreatePngFromPdf() 
        {

            try
            {

                string PDFLocation = string.Format(@"\\XXXX\{0}\{1}\{2}.pdf", Yr, Loc.Substring(0, 4), Loc.Substring(4, 4));
                Utilities.WebPDF.PDF WebPDF = new DocuvaultMVC.Utilities.WebPDF.PDF();

                WebPDF.Credentials = new NetworkCredential(@"xyz", "xyz");
                byte[] png = WebPDF.StreamPdfPageAsPngResize(PDFLocation,PageNumber, 612, 792);

                MemoryStream ms = new MemoryStream(png);
                MemoryStream stream = new MemoryStream();
                int newWidth = 612;
                int newHeight = 792;
                System.Drawing.Image newImg = System.Drawing.Image.FromStream(ms);

                Bitmap temp = new Bitmap(newWidth, newHeight, newImg.PixelFormat);
                Graphics newImage = Graphics.FromImage(temp);
                newImage.DrawImage(newImg, 0, 0, newWidth, newHeight);
                newImg.Dispose();

                temp.Save(stream, ImageFormat.Png);
                stream.WriteTo(Response.OutputStream);
                temp.Dispose();
                stream.Dispose();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
        }

【问题讨论】:

  • 哦,天哪,如果抛出异常,这将泄漏句柄 :-) 在处理流和 GDI+ 对象等一次性资源时,您真的应该考虑使用using
  • Pinu,有关异常的一些详细信息会有所帮助。还有调用 this 的上下文。 (ASPX还是ASHX,哪个事件?)代码本身基本没问题,除了@Darin做的注释。
  • @Darin,我不明白你,你能给我一个例子,说明我如何使用它吗?
  • @Pinu,你得到了什么确切的例外? DocuvaultMVC.Utilities.WebPDF 是什么?
  • 这是对我正在使用的网络服务的引用

标签: c# asp.net


【解决方案1】:

这与您的问题没有直接关系,但是我在做其他事情时遇到了同样的异常,所以我想我会把这个答案放在这里以供后代使用......

我只是在主页呈现时才收到此异常,而不是在转到相关的控制器操作时。

随后发生了很多令人头疼的事情,直到我意识到我使用的是 Html.Action(它运行操作并发出内联 HTML)而不是 Url.Action(它生成 URL)。

【讨论】:

  • 是的!谢谢 - 对于任何想坚持使用 @Html 助手的人 - 你也可以使用 @Html.ActionLink(xxx)
【解决方案2】:

在我的情况下,原因是 Controller.File 方法中的参数错误。

第三个参数为null的Controller.File方法将在浏览器窗口中渲染图像:

public ActionResult GenerateImage(...)
{
    ...
    return File(fileResult.Buffer, fileResult.ContentType, null);
}

第三个参数为filename的Controller.File方法将触发在浏览器中下载图片:

public ActionResult GenerateImage(...)
{
    ...
    return File(fileResult.Buffer, fileResult.ContentType, "image.jpg");
}

第三个参数为extension的Controller.File方法会报错:OutputStream is not available when a custom TextWriter is used

public ActionResult GenerateImage(...)
{
    ...
    return File(fileResult.Buffer, fileResult.ContentType, ".jpg");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    相关资源
    最近更新 更多