Search code examples
javaplayframeworkdownloadfilenamesplayframework-2.0

Downloaded file with Play Framework has wrong filename


I'm using Play Framework 2.0.2 to create an application that modifies Excel files uploaded by the user. Once the Excel file is uploaded and modified (server-side), the file is automatically downloaded by the user's browser.

However, using this code:

public static Result upload() throws IOException {
    Http.MultipartFormData body = request().body().asMultipartFormData();
    Http.MultipartFormData.FilePart filePart = body.getFile("uploadedFile");

    modifyExcelFile(filepart.getFile()); // this method modifies the uploaded Excel file, and copies it to a file named "copy.xlsx"

    return ok(new File("copy.xlsx"));
}

the file that is downloaded by the client will be named after the current Controller. For example, if my Controller is named UploadController, the downloaded file is surprisingly named uploadcontroller.xlsx.

Any idea on how I could modify my code in order to have a tighter control on the downloaded file's name? I would like the downloaded file to be named copy.xlsx, not uploadcontroller.xlsx.


Solution

  • Just add this in the response header:

    response().setHeader("Content-Disposition", "attachment; filename=FILENAME");
    

    Where FILENAME is the name you want your file to have.