spring boot 中文名称文件下载 显示乱码

2018-10-26  本文已影响0人  金刚_30bf

使用spring boot 提供下载功能 , 当下载文件的为中文名称时, 下载本地却显示为乱码 .

需要在下载文件头处对文件名进行编码 .

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        String filename = "";
        try {
            filename = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }
上一篇 下一篇

猜你喜欢

热点阅读