meridbt
meridbt

Reputation: 387

How to specify a download filename in a REST controller?

there is a REST controller with the GET mapped method:

@GetMapping(value="/{filename}", produces= MediaType.APPLICATION_PDF_VALUE)
    public @ResponseBody byte[] letItTry(@PathVariable("filename") String filename) {
        try {                        
            return download(filename);
        }
        catch (Exception ex) {
            return new byte[0];
        }
    }

and download method looks like this:

public byte[] download(String filename) {  
        try(var fis= new FileInputStream(new File(filename))) {
            return fis.readAllBytes();
        } 
        catch (Exception ex) {
            return new byte[0];
        }
    }

When the endpoint is being called from the web browser, it returns the PDF document with default RestController name, for instance, "Test.pdf". Is there a way to force controller to return the file fith given custom name?

Upvotes: 1

Views: 3849

Answers (1)

Tal Glik
Tal Glik

Reputation: 510

You should add HttpServletResponse to your Get method and set the file name there using the header:

   public @ResponseBody byte[] letItTry(@PathVariable("filename") String filename, HttpServletResponse response) {
    try {
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        return download(filename);
    }
    catch (Exception ex) {
        return new byte[0];
    }
}

Upvotes: 4

Related Questions