Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 273
TreantBG Avatar asked Mar 24 '23 20:03

TreantBG


1 Answers

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().

like image 56
BalusC Avatar answered Mar 29 '23 23:03

BalusC