Primefaces fileDownload non-english file names cor

2019-02-24 01:14发布

I am using Primefaces 3.2. I've got problems with using primefaces fileDownload. I can upload the files and keep their non-english name on the server (in my case this is Russian). However, when I use p:fileDownload to download the uploaded files I cannot use Russian letters since they get corrupt. It seems that the DefaultStreamedContent class constructor accepts only Latin letters. I am doing everything according to the showcase on the primefaces website as shown below.

public FileDownloadController() {          
    InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/images/optimusprime.jpg");  
    file = new DefaultStreamedContent(stream, "image/jpg", "downloaded_optimus.jpg");  
}

Any ideas how I can solve my problem?

Thanks, in advance.

1条回答
Evening l夕情丶
2楼-- · 2019-02-24 01:31

This is fixed in the upcoming PrimeFaces 6.2, but for earlier versions the fix below needs to be applied. In a link in the comments below a reference to a PrimeFaces issue was posted which contains info that the fix below does work for Chrome, IE and Opera but not for FireFox (no version mentioned, nor is 'Edge' mentioned)

Workaround

Try to encode your file name in application/x-www-form-urlencoded MIME format (URLEncoder).

Example:

public StreamedContent getFileDown () {
        // Get current position in file table
        this.currentPosition();
        attachments = getAttachments();
        Attachment a = getAttachmentByPosition( pos, attachments );

        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        // Detecting MIME type
        String mimeType = fileNameMap.getContentTypeFor(a.getAttachmentName());
        String escapedFilename = "Unrecognized!!!";
        try {
            // Encoding
            escapedFilename = URLEncoder.encode(a.getAttachmentName(), "UTF-8").replaceAll(
                    "\\+", "%20");
        } catch (UnsupportedEncodingException e1) {         
            e1.printStackTrace();
        }
        // Preparing streamed content
        fileDown = new DefaultStreamedContent( new ByteArrayInputStream( a.getAttachment() ),
                mimeType, escapedFilename);
        return fileDown;
    }
查看更多
登录 后发表回答