亲身实测可用的java实现wordxlsxpdf文件下载功能

本文参考原文-http://bjbsair.com/2020-03-22/tech-info/3621.html
在SpringMVC的开发过程中,有时需要实现文档的下载功能。word,excel,pdf作为大家最常用的办公程序,它的文件传输就显得尤为重要,本文通过使用spring 提供的Resource封装来实现实现word/xlsx/pdf文件下载功能。话不多说。

亲身实测可用的java实现word/xlsx/pdf文件下载功能

亲身实测可用的java实现word/xlsx/pdf文件下载功能

package com.davidwang456;  
  
import java.io.File;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.core.io.FileSystemResource;  
import org.springframework.core.io.Resource;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseBody;  
import org.springframework.web.bind.annotation.RestController;  
@RestController  
public class DownloadController {  
	private static final String APPLICATION_PDF="application/pfd";  
	private static final String APPLICATION_WORD="application/msword";  
	private static final String APPLICATION_EXCEL="application/vnd.ms-excel;charset=utf-8";	  
	@RequestMapping(value="/download",method=RequestMethod.GET,produces=APPLICATION_PDF)  
	@ResponseBody  
	public Resource download(HttpServletRequest req,HttpServletResponse resp) {  
		String file);  
		File file=getFile(fileName);  
		String suffix=fileName.substring(fileName.lastIndexOf(".")+1);  
		if(suffix.equalsIgnoreCase(APPLICATION_PDF)) {  
			resp.setContentType(APPLICATION_PDF);  
			resp.setHeader("Content-Disposition", "inline;filename="+file.getName());  
		}else if(suffix.equalsIgnoreCase(APPLICATION_WORD)) {  
			resp.setContentType(APPLICATION_WORD);  
			resp.setHeader("Content-Disposition", "attachment;filename="+file.getName());  
		}else if(suffix.equalsIgnoreCase(APPLICATION_EXCEL)) {  
			resp.setContentType(APPLICATION_EXCEL);  
			resp.setHeader("Content-Disposition", "attachment;filename="+file.getName());  
		}	  
		resp.setHeader("Content-Length", String.valueOf(file.length()));  
		return new FileSystemResource(file);  
	}  
	private static File getFile(String fileName) {  
		File file=new File( "path"+fileName);  
		if(!file.exists()) {  
			System.out.println("指定路径下的文件不存在!");  
		}  
		return file;  
	}  
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值