spring mvc下载文件简绍和常见问题

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

转载于:https://my.oschina.net/u/2555967/blog/3027171

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值