完整的文件下载例子

前段,js 下载

  1,采用ajax异步调用,后台生成文件,返回前段,文件的名称

  2,文件名称采用唯一的UUID生成

 function ajaxExport(){
                var name = $('#name').val();
                if(name == undefined ){
                    name = "";
                }
  
                $.post("${ctx}/xzcf/todo/ajaxExport",parameters,function(data){
                    top.layer.closeAll('loading');
                    if(data.ok){
                        top.layer.confirm('文件导出成功,是否下载?', {
                            btn: ['下载','取消']
                        },function(){
                            location.href="${ctx}/xzcf/todo/download?fileId="+data.fileId+"&ext="+data.ext;
                            top.layer.closeAll();
                        });
                    }else{
                        errorx("文件导出失败!")
                    }
                },"json");
            }

后端处理

	@ResponseBody
	@RequestMapping(value = "ajaxExport")
	public Map<String, Object> exportFile( @RequestParam Map<String, Object> parameters, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		boolean ok = false;
		String fileId = IdGen.uuid();
		String ext = null;
		// 获取有效数据
		List<MapEntity> datas = xzcfToDoService.findFeedList(parameters);
		try {
			// 生成对应的excel文件
			File file = xzcfToDoService.createPushExcel(datas, fileId);
			if (file != null) {
				ok = true;
				ext = Files.getFileExtension(file.getName());
			}
		} catch (IOException e) {}
		// 返回ajax 数据
		Map<String, Object> result = Maps.newHashMap();
		result.put("ok", ok);
		result.put("fileId", fileId);
		result.put("ext", ext);
		return result;
	}

 

@Transactional(readOnly = false)
	public File createPushExcel(List<MapEntity> entities,String fileId) throws IOException {
		// 1. 生成一个file 文件
		File resultFile  = null;
		try {
			if(StringUtils.isBlank(fileId)){
				fileId = IdGen.uuid();
			}
			String[] headers = {"主体名称"};
			String[] keys = {"cfxdrmc"};
			
			ExportExcel  ex =new ExportExcel("行政处罚反馈数据", headers).setDataList1(entities, keys);
			String tmpPath = DataUtils.getServletContextRealPathResolver().get(Global.getConfig("tmpPath"));
			File dir = new File(tmpPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			resultFile = new File(tmpPath + "/" + fileId + ".xls");
			FileOutputStream os = new FileOutputStream(resultFile);
			ex.write(os);
			os.flush();
			os.close();
			
   	   } catch (Exception e) {
   		   e.printStackTrace();
   	   }
		   return resultFile;
	  }

下载代码,

  URLEncoder.encode 编码,防止,下载中文乱码

@RequestMapping("download")
	public String download(String fileId, String ext, HttpServletRequest request, HttpServletResponse response) {
		try {
			response.reset();
			response.setContentType("application/octet-stream");
			String fileName = URLEncoder.encode(xzcfName+"."+ext, "utf-8");
			String tmpPath = DataUtils.getServletContextRealPathResolver().get(Global.getConfig("tmpPath"));
			File file = new File(tmpPath + "/" + fileId + "." + ext);
			System.out.println(file.exists());
			InputStream is = new FileInputStream(file);
			OutputStream os = response.getOutputStream();
			response.addHeader("Content-Disposition", "attachment; filename=\""+ fileName +"\""); 
			IOUtils.copy(is, os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值