【问题标题】:Grails - Displaying PDF in browser rather than downloadingGrails - 在浏览器中显示 PDF 而不是下载
【发布时间】:2014-09-11 12:36:55
【问题描述】:

在我的 Grails 应用程序中,我有一个返回 PDF 文件的控制器函数。

当我调用 URL(返回文件)时,它会下载文件,而不是在浏览器中显示 PDF 文件。

当我从其他网站打开其他 pdf 文件时,它会显示在浏览器中.. 所以我认为这与我返回的响应有关?

def separator = grailsApplication.config.project.separator.flag
def path = grailsApplication.config.project.images.path+"public/"+user.id+"/"
render(contentType: "multipart/form-data", file: new File(path+note.preview), fileName: note.preview)

我需要更改 contentType 吗? (我试着让它 /application/pdf 但没用?..仍然下载。

【问题讨论】:

    标签: java file grails outputstream


    【解决方案1】:

    尝试将content-disposition 设置为内联。 Content-Type 告诉浏览器它是什么类型的内容,但处置告诉浏览器如何处理它。

    更多信息in this answer

    【讨论】:

    • 如何设置内容配置.. 当我尝试 response.setHeader 然后调用 render 之后,我认为它会覆盖它?
    • 可以直接写入输出流吗?比如:response.outputStream << your_file response.outputStream.flush()
    • 我试过以下没有运气---> response.setHeader "Content-disposition", "inline; filename="+note.preview response.contentType = 'application/pdf' response .outputStream
    • 我得到“加载文档失败”,所以它似乎正确地获取文件..但无法正确显示它
    • 您确定 PDF 文件的内容?当它作为附件发送时,它会在 Adob​​e Reader 中打开吗?可以试试其他浏览器吗?
    【解决方案2】:

    由于返回“文件”对象而不是字节[] 对象,导致某些东西被破坏。

    所以我添加了以下几行。

    byte[] DocContent = null;
    DocContent = getFileBytes(path+note.preview);
    
    response.setHeader "Content-disposition", "inline; filename="+note.preview+""
    response.contentType = 'application/pdf'
    response.outputStream << DocContent
    response.outputStream.flush()
    
    
    public static byte[] getFileBytes(String fileName) throws IOException
    {
        ByteArrayOutputStream ous = null;
        InputStream ios = null;
        try
        {
            byte[] buffer = new byte[4096];
            ous = new ByteArrayOutputStream();
            ios = new FileInputStream(new File(fileName));
            int read = 0;
            while ((read = ios.read(buffer)) != -1)
                ous.write(buffer, 0, read);
        }
        finally
        {
            try
            {
                if (ous != null)
                    ous.close();
            }
            catch (IOException e)
            {
                // swallow, since not that important
            }
            try
            {
                if (ios != null)
                    ios.close();
            }
            catch (IOException e)
            {
                // swallow, since not that important
            }
        }
        return ous.toByteArray();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 2016-07-31
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      相关资源
      最近更新 更多