TreantBG
TreantBG

Reputation: 1222

JSF 2 download file with cyrillic name

I have a datatable with files and button to download the selected file.

If the filename is with cyrillic symbols the browser says "Unknown file type" Example: i have file "асдасд.png" and i click download browser response enter image description here

there is my download method

public void download(Files file) {
    try {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.setResponseHeader("Content-Type", "application/x-download");
        externalContext.setResponseHeader("Content-Length", file.getFileContent().length+"");
        externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + file.getFilename() + "\"");
        externalContext.getResponseOutputStream().write(file.getFileContent());
        facesContext.responseComplete();
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (Exception e){
        e.printStackTrace();
    }
}

im pretty sure i need to encode the filename to UTF-8 but i dont know how... please help.

Upvotes: 4

Views: 1588

Answers (1)

BalusC
BalusC

Reputation: 1108692

Use URLEncoder.

URLEncoder.encode(file.getFileName(), "UTF-8")

Note that this is already implicitly done by OmniFaces Faces#sendFile(). So if you happen to use OmniFaces already, then you can just directly make use of it.

The "unknown file type" part is caused by using an unsupported content type. You should be using the right content type, which is image/png for PNG files. You can use ExternalContext#getMimeType() to get the right content type based on a file name. This is also already implicitly done by Faces#sendFile().

Upvotes: 7

Related Questions