Spring MVC文件下载的文件名编码问题

Spring MVC做文件下载功能时,遇到了文件名编码问题。经过百度,参考了以下两篇文章,解决了编码问题。

http://www.iefans.net/xiazai-wenjian-http-bianma-content-disposition/

https://yq.aliyun.com/articles/38945

最终代码如下:

    public ResponseEntity<InputStreamResource> downloadFile(Path filePath) 
            throws FileNotFoundException {
        File file = filePath.toFile();
        
        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        
        HttpHeaders respHeaders = new HttpHeaders();
        respHeaders.set(HttpHeaders.CONTENT_TYPE, mimeType);
        respHeaders.setContentLength(file.length());
        String encodedFileName = file.getName();
        try {
            encodedFileName = URLEncoder.encode(encodedFileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("文件名编码错误!", e);
        }
        respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\""
                + "; filename*=UTF-8''" + encodedFileName);
        
        InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
        return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
    }

先对原始文件名按UTF-8编码,再设置Content-Disposition。Content-Disposition中设置了两次filename,是为了兼容更多浏览器。

posted @ 2017-10-27 19:52  xiao_tan  阅读(638)  评论(0)    收藏  举报