文件下载--解决文件名字乱码问题

@GetMapping("download")
@ResponseBody
public void download(String fileName, @RequestParam(required = false) String newName, HttpServletResponse response) {
    String path = path; //  C:\\upload\\
    File file = new File(path, fileName);
    InputStream inputStream = null;
    OutputStream outputStream = null;
    if (file.exists()) {
        try {
            String filename = StringUtils.isNotBlank(newName) ? newName : file.getName();
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "ISO-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream;charset=utf-8");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
    原文作者:可乐止饱
    原文地址: https://blog.csdn.net/burmem/article/details/103919113
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞