1. 使用Servlet API 原生方式下載
//設置編碼爲UTF-8
@RequestMapping(value = "/downTemplate",produces="text/html;charset=UTF-8")
public void downTemplate(HttpServletResponse response) throws FileNotFoundException {
//獲取文件(web項目中獲取絕對地址)
File file = ResourceUtils.getFile( ResourceUtils.CLASSPATH_URL_PREFIX+"templates/事件測試.xlsx" );
//設置下載響應頭
response.addHeader("Content-Disposition", "attachment;fileName=" + "x.xlsx");// 設置文件名
try {
//複製及寫到響應流中
byte[] bytes = FileUtils.readFileToByteArray( file );
IOUtils.write( bytes,response.getOutputStream() );
} catch (Exception e) {
e.printStackTrace();
}
}
2. 使用Spring MVC封裝的方式下載
3. 使用Maven時Excel等資源文件損壞問題
<!-- 解決Excel文件損毀問題 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
4. VUE下載文件
down(){
axios.get('/event/collectEvent/downTemplate',{
//設置響應體(必須)
responseType: 'blob'
}).then(res => {
let url = window.URL.createObjectURL(new Blob([res]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xlsx')
document.body.appendChild(link)
link.click()
})
.catch(err => {
console.log(err);
})
}