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

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

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

记录:

    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();
				}
			}
		}
    }

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值