文件下載--解決文件名字亂碼問題

@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();
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章