問題:項目中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();
}
}