java后台实现批量下载文件_Java后台Controller实现文件下载操作

代码

参数:

1.filePath:文件的绝对路径(d:\download\a.xlsx)

2.fileName(a.xlsx)

3.编码格式(GBK)

4.response、request不介绍了,从控制器传入的http对象

代码片.

//控制器

@RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD)

public void downLoad(String filePath, HttpSelVuKjOlowbrvletResponse response, HttpServletRequest request) throws Exception {

boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request);

if(is)

System.out.println("成功");

else

System.out.println("失败");

}

//下载方法

public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request

实现效果

1.火狐浏览器效果

06c399d9e08bc14aaad2cf60e9dc256e.png

2.chrome效果,自动下载

71b62063d190ddc1488cd2265f4b259d.png

补充知识:文件上传/下载的几种写法(java后端)

文件上传

1、框架已经帮你获取到文件对象File了

public boolean uploadFileToLocale(File uploadFile,String filePath) {

boolean ret_bl = false;

try {

InputStream in = new FileInputStream(uploadFile);

ret_bl=copyFile(in,filePath);

} catch (Exception e) {

e.printStackTrace();

}

return ret_bl;

}

public boolean copyFile(InputStream in,String filePath) {

boolean ret_bl = false;

FileOutputStream os=null;

try {

os = new FileOutputStream(filePath,false);

byte[] b = new byte[8 * 1024];

int length = 0;

while ((length = in.read(b)) > 0) {

os.write(b, 0, length);

}

os.close();

in.close();

ret_bl = true;

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

if(os!=null){

os.close();

}

if(in!=null){

in.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return ret_bl;

}

}

2、天了个撸,SB架构师根本就飘在天空没下来,根本就没想文件上传这一回事

public String uploadByHttp(HttpServletRequest request) throws Exception{

String filePath=null;

List fileNames = new ArrayList<>();

//创建一个通用的多部分解析器

CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

//判断 request 是否有文件上传,即多部分请求

if(multipartResolver.isMultipart(request)){

//转换成多部分request

MultipartHttpServletRequest multiRequest =multipartResolver.resolveMultipart(request);

MultiValueMap multiFileMap = multiRequest.getMultiFileMap();

List fileSet = new LinkedList<>();

for(Entry> temp : multiFileMap.entrySet()){

fileSet = temp.getValue();

}

String rootPath=System.getProperty("user.dir");

for(MultipartFile temp : fileSet){

filePath=rootPath+"/tem/"+temp.getOriginalFilename();

File file = new File(filePath);

if(!file.exists()){

file.mkdirs();

}

fileNames.add(temp.getOriginalFilename());

temp.transferTo(file);

}

}

}

3、神啊,我正在撸框架,请问HttpServletRequest怎么获取!!!!

(1)在web.xml中配置一个监听

org.springframework.web.context.request.RequestContextListener

(2)HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

文件下载(直接用链接下载的不算),这比较简单

1、本地文件下载(即文件保存在本地)

public void fileDownLoad(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws Exception {

response.setCharacterEncoding("UTF-8");

//设置ContentType字段值

response.setContentType("text/html;charset=utf-8");

//通知浏览器以下载的方式打开

response.addHeader("Content-type", "appllication/octet-stream");

response.addHeader("Content-Disposition", "attachment;filename="+fileName);

//通知文件流读取文件

InputStream in = request.getServletContext().getResourceAsStream(filePath);

//获取response对象的输出流

OutputStream out = response.getOutputStream();

byte[] buffer = new byte[1024];

int l

2、远程文件下载(即网上资源下载,只知道文件URI)

public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){

try {

urlStr=urlStr.replaceAll("\\\\", "/");

URL url = new 编程客栈URL(urlStr);

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

//设置超时间为3秒

conn.setConnectTimeout(3*1000);

//防止屏蔽程序抓取而返回403错误

conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

//得到输入流

InputStream inputStream = conn.getInputStream();

response.reset();

response.setContentType("application/octet-stream; charset=utf-8");

response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1"));

//获取响应报文输出流对象

//获取response对象的输出流

OutputStream out = response.getOutputStream();

byte[] buffer = new byte[1024];

int len;

//循环取出流中的数据

while((len = in.read(buffer)) != -1){

out.write(buffer,0,len);

}

} catch (Exception e) {

e.printStackTrace();

}

}

以上这篇Java后台Controller实现文件下载操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

本文标题: Java后台Controller实现文件下载操作

本文地址: http://www.cppcns.com/ruanjian/java/352090.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值