java实现下载文件到浏览器默认路径

1、错误方法:

直接在ajax中传path到后台,下载后放在response中返回,会出现错误,因为ajax只接受字符串等类型,不能解析头文件

2、解决:

2.1方案一

可以直接将前台改成超链接,在href中跳转到controller,可以执行下载(但是这个方法不方便传参),自己尝试在href中传path没有成功

2.2方案二

又要传参,又要放在头文件中返回怎么处理呢?

查阅网上各博客,都说用 window.location.href =代替ajax,但没有具体实施方案

下面给出自己尝试后成功的例子(思路:先用ajax将参数传到后台,存在session中,在ajax请求成功后,使用window.location.href跳转到执行下载的controller)

前台:

$(".fa-download").click(function() {
			var path = $(this).attr("value");
			$.ajax({
	            url: "mail/preDownLoad",
	            type: "post",
	            dataType: "text",
	            data:{"path":path},
	            success: function (data) {
	            	alert("成功")
	                 if (!isEmpty(path)) {
	                     window.location.href = "mail/downLoad";                         
	                } else {
	                   alert("附件路径丢失")
	                } 
	            },
	            error: function (err) {
	            	alert("下载失败")
	               /*   $.dialog.alert("下载失败"); */
	            }
	        });      
		});

后台:

过渡的controller

@RequestMapping("/preDownLoad")
	public String preDownLoad(String path, HttpSession session) {
		session.setAttribute("path", path);
		return "message/informationDetails";
	}

执行下载的controller

@RequestMapping("/downLoad")
	public void downLoad(HttpSession session, HttpServletResponse response) {
		String path = (String) session.getAttribute("path");
		// path是指欲下载的文件的路径
		File file = new File(path);
		// 取得文件名
		String filename = file.getName();
		// 以流的形式下载文件
		InputStream fis;
		try {
			fis = new BufferedInputStream(new FileInputStream(path));

			byte[] buffer = new byte[fis.available()];

			fis.read(buffer);

			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-disposition", "attachment;filename=" + new String(filename.getBytes()));
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setContentType("application/x-msdownload");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
			System.out.println("下载成功");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

参考:https://blog.csdn.net/Gunc_/article/details/72771134

https://blog.csdn.net/pp_fzp/article/details/78296407

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值