Java下载文件
文件下载小技巧:
由于不能使用ajax直接下载文件,因此要做到无刷新页面下载,可以采用以下方案:
1.使用ajax提交生成临时文件存放到服务器,并返回文件名(建议文件路径放置在指定的目录下,只返回文件名即可,全文件名需要js文件中做转码)
2.根据返回结果,发送下载请求,参数:文件名
JS(前端采用layui),返回json格式: {"message":"测试导出数据.xlsx","result":true}
// 下载文件$("#exportExt").on("click",function(){ // 友好提示信息 var msgIndex = layer.msg('数据下载中,由于数据较大,请耐心等候...11', {icon: 16,scrollbar: false,time: 0}); $.ajax({ type : 'post', async : false, // 默认异步true,false表示同步 url : 'exp/createExpFile', // 生成文件,保存在服务器 dataType : 'json', // 服务器返回数据类型 data : { startDate : $("#startDate").val(), endDate : $("#endDate").val() }, success : function(data) { // 关闭提示信息 layer.close(msgIndex); if(data.result == true) { window.location.href='test/downLoad?fileName=' + data.message; } }, error : function(XMLHttpRequest, textStatus, e) { // 关闭提示信息 layer.close(msgIndex); layer.alert('导出数据失败', {icon: 5}); } });});
Controller
@AutowiredTestService testService;/** * @描述: 生成下载文件 * @return * @日期 2019年6月20日 */@RequestMapping("createExpFile")@ResponseBodypublic String createExpFile(){ return testService.createExpFile();}/** * @描述: 导出下载文件 * @日期 2019年6月20日 */@RequestMapping("downLoadExt")@ResponseBodypublic void downLoadExt(){ testService.downLoadExt();}
Service
下载文件请参考java导出数据到Excel文件
@Autowiredpublic HttpServletResponse response;// 临时文件目录,这里指定一个目录,实际应用建议动态获取目录private static final String tempPath = "e:"+ "tempFile" + File.separator + "download" + File.separator;/** * @描述: 生成下载文件 * @return * @日期 2019年6月20日 */public String createExpFile() { // 文件存放目录 String savePath = tempPath; // 文件存放名称 String fileName = "测试下载文件.xlsx"; // 1.获取要导出的数据信息 List<String[]> dataList = getDownLoadData(); // 2.导出信息到Excel文件(参考https://blog.51cto.com/blogger/publish/2411391) boolean expFlag = ToolExcelExp.exportBigDataExcel(savePath + fileName, dataList); MessageBean messageBean = new MessageBean(); messageBean.setResult(expFlag); messageBean.setMessage(fileName); return JSONObject.toJSONString(messageBean);}/** * @描述: 导出下载文件 * @日期 2019年6月20日 */public void downLoadExt() { Map<String, Object> paramMaps = getMaps(); // 文件存放目录 String savePath = tempPath; // 文件存放名称 String fileName = paramMaps.get("fileName").toString(); // 文件下载 ToolDownLoad.downloadFile(response, savePath + fileName); System.out.println("导出完毕");}
文件下载工具类
import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import javax.servlet.http.HttpServletResponse;public class ToolDownLoad { /** * @描述: 文件下载 * @param response * @param filePath 要下载的文件全路径 * @日期 2019年6月19日 */ public static void downloadFile(HttpServletResponse response, String filePath) { response.setContentType("text/html;charset=utf-8"); System.out.println(filePath); File file = new File(filePath); String fileName = file.getName(); long fileLength = file.length(); if (file.exists()) { FileInputStream fis = null; BufferedInputStream bis = null; try { response.setContentType("application/force-download");// 设置强制下载不打开 response.addHeader("Content-Disposition", "attachment; fileName=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));// 设置文件名 response.setHeader("Content-Length", String.valueOf(fileLength)); byte[] buffer = new byte[1024]; fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("success"); } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } // 下载完毕,删除文件 file.delete(); } } }}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。