• java下载Excel报500,下载的excel文件乱码打不开


    解决方法:这里是下载excel文件有问题,下载的时候指定响应内容类型为excel

    response.setContentType("application/vnd.ms-excel");
    
    • 1

    记录:

        public void downloadLocal(HttpServletResponse response, String fileName) throws IOException {
            // 拼接文件路径
            String filePath = "file" + File.separator + fileName;
            log.info("下载文件路径:" + filePath);
            log.info("下载文件名称:" + fileName);
            String newFilePath = JsoupUtils.clean(filePath);
            ClassPathResource cpr = new ClassPathResource(newFilePath);
    		log.info("ClassPathResource:" + cpr);
            // 设置输出的格式
            response.reset();
    		//正常输出流
    		if(fileName.contains(".xls")){
    			response.setContentType("application/vnd.ms-excel");
    		}else{
    //			response.setContentType("application/octet-stream");
    			response.setContentType("bin");
    		}
    		response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    		InputStream inStream = null;
    		OutputStream outputStream = null;
    		try{
    			inStream = cpr.getInputStream();
    			outputStream = response.getOutputStream();
            	// 循环取出流中的数据
            	byte[] b = new byte[100];
            	int len;
                while ((len = inStream.read(b)) > 0) {
    				outputStream.write(b, 0, len);
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }finally {
    			if (inStream!=null){
    				try {
    					inStream.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			if (outputStream!=null){
    				try {
    					outputStream.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    刚开始使用response.setContentType("bin")本地在postman上跑是是没有问题的,原始服务器也没问题,同样的代码换服务器跑就有问题。查看日志,也没报错,但是返回状态却是500,保存excel打开是乱码。
    首先,乱码打不开,要考虑输出格式的问题。bin是什么类型?好像是和application/octet-stream一样,网上对bin介绍太少,下载文件如果知道文件的类型,还是输出相对应的文件类型,不要用bin这种,可能是文件类的输出类型,不然会出现一些莫名奇妙的问题

  • 相关阅读:
    【杂记】git管理工具的相关应用
    redis学习-linux上redis的安装
    wsl kali-linux 安装记录
    【计算机视觉】CVPR 23 | 视觉 Transformer 全新学习范式!用长尾数据提升ViT性能
    大型客户关系管理系统源码CRM
    汇编-MOVSXD64位带符号扩展传送
    阿里P8大能倾力编撰的“Java 进阶面试手册”,助力跳槽外包毕业生秋招收获大厂offer
    Intel E810 DDP在VPP offload加速框架中的应用
    外贸公司官网产品展示网站搭建源码
    laravel 凌晨0点 导出数据库
  • 原文地址:https://blog.csdn.net/shujuku____/article/details/126070078