[英]Grails - Displaying PDF in browser rather than downloading
在我的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但是没有用?还是下载了。
尝试将content-disposition
为内联。 Content-Type
告诉浏览器它是什么类型的内容,但是处置告诉浏览器如何处理它。
本答案中的更多信息
通过返回“File”对象而不是byte []对象,有些东西会被破坏。
所以我添加了以下几行。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.