zoukankan      html  css  js  c++  java
  • springboot项目中文件的下载(解决中文乱码问题)

    最近使用springboot项目,一直以来文件都以英文格式存储,这次使用的是xls文件下载,文件名为中文的,特此记录下中文文件名的下载以及springboot中下载路径报错问题。

    正文

    在使用springboot导出excel的时候,出现了两个问题:如下

    1. 导出的时候中文名乱码问题

    如:鑱旂綉鍗煎叆妯℃澘.xlsx

    2. 导出的时候springboot路径问题:在jar项目后会默认多一个!,导致路径错误。

    具体实现思路是:

    首先拿到文件名,然后拿到父路径和文件名,创建一个File,然后将此file使用response写出到客户端。对于获取父路径:使用的是类的加载器,getResource(“name”)得到的URL对象,然后获取的url.getPath(),这就造成了获取File时候创建的路径多了个!。

    之后进行更改,因为获取File文件之后还是需要拿到InputStream。所以这里直接使用的是:类的加载器直接获取资源作为InputStream

    接下来就是解决乱码问题:

    名字进行重新编码:

    然后设置一些相应类型和响应头:将流作为相应

    完整版代码如下:

     String file_name = "用户导入模板.xlsx";
            try{
                OutputStream os = response.getOutputStream();
                String fileName = new String(file_name.getBytes("GBK"),"ISO-8859-1");
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("excelTemplate/" + file_name);
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition","attachment;fileName=" + fileName);
                int len = 0;
                byte[] b = new byte[1024];
                while ((len = is.read(b, 0, b.length)) != -1) {
                    os.write(b, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

    这样就可以下载文件了并且不会出现乱码。

     

     目前还没有遇到别的问题,有别的问题在更新。

    2018-08-27更新:

    在最近使用下载的时候,发现转来转去的编码比较麻烦,发现了一个 URLEncoder.encode(fileName,"UTF-8") 的方法,特此记录下。

     String fileName = path.substring(path.lastIndexOf("\") +1 ,path.length());
            File file = new File(path);
            if (!file.exists()){
                logger.error("路径有误,文件不存在!");
            }
            //new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
            response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            response.setContentType("content-type:octet-stream");
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0 ;
            while ((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer ,0 , len);
            }
            inputStream.close();
            outputStream.close();

    使用 URLEncoder.encode(fileName,"UTF-8"),将编码转换为utf-8编码。

  • 相关阅读:
    解析Javascript事件冒泡机制
    LeetCode——Flatten Binary Tree to Linked List
    流动python
    HDU2586
    Cannot find ActionMappings or ActionFormBeans collection
    reactor设计模式
    简单的Ajax应用实例
    CString——Left、Right、Find、ReverseFind
    MATLAB新手教程
    八大排序算法总结
  • 原文地址:https://www.cnblogs.com/chenmc/p/9413553.html
Copyright © 2011-2022 走看看