Java:excel模板文件打包後亂碼問題

問題:項目中resources目錄下的excel模板打包後文件亂碼了
原因:maven打包會對資源統一編碼
在這裏插入圖片描述
解決方式:忽略maven打包時需要編碼的文件

在pom.xml加入下面代碼

  <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.7</version>
        <configuration>
          <encoding>UTF-8</encoding>
          <nonFilteredFileExtensions>
            <nonFilteredFileExtension>xls</nonFilteredFileExtension>
            <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
            <nonFilteredFileExtension>dat</nonFilteredFileExtension>
          </nonFilteredFileExtensions>
        </configuration>
      </plugin>

模板下載前端代碼AngularJS:

$scope.downTemp = function () {
        $http({
            method: 'post',
            url: 'load/downloadTemp',
            responseType: 'arraybuffer',
        }).success(function (data) {
            var fileName = "導入模板.xls";
            var url = window.URL.createObjectURL(new Blob([data],{type:"application/vnd.ms-excel"}));
            var link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download',fileName);
            document.body.appendChild(link);
            link.click();
        })
    }

後端:

 @RequestMapping("/downloadTemp")
    public void downloadTemp(HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;fileName=導入模板.xls");
        try {
            OutputStream out = response.getOutputStream();
            Resource resource = new ClassPathResource("templates/導入模板.xls");
            InputStream in = new FileInputStream(resource.getFile());
            IOUtils.copy(in,out);
            out.flush();
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章