Tyler Evans
Tyler Evans

Reputation: 579

Grails - Displaying PDF in browser rather than downloading

In my Grails applications, I have a controller function to return a PDF file.

When I make a call to the URL (to return the file), It downloads the file, rather than displaying the PDF file in the browser.

When I open other pdf files from other websites, it displays in browser.. so I think it has something to do with my returned response?

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)

Do I need to change the contentType? (I kind of tried to make it /application/pdf but didnt work?..still downloads.

Upvotes: 3

Views: 2904

Answers (2)

Tyler Evans
Tyler Evans

Reputation: 579

There was something getting corrupt by returning a "File" object rather than a byte[] object.

So I added the following lines.

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();
}

Upvotes: 1

Praba
Praba

Reputation: 1381

Try setting content-disposition to inline. Content-Type tells the browser what type of content it is but the disposition tells the browser on how to handle it.

More information in this answer

Upvotes: 4

Related Questions