业务功能:下载文件

【业务功能:下载文件】

每次使用到“下载文件”都会找以前的代码copy,我受够了去找以前代码的过程,我把它记录到博客里

前端部分

// 不能使用ajax请求
var url = ServerPath  + "/dxq/dwld.action?token="+$.cookie("token")+"&id="+id
window.open(url);

后端Controller

	/**
	 * 数据下载
	 */
	@RequestMapping(value="download", method = RequestMethod.GET)
	@ResponseBody
	public ResponseData download(HttpServletRequest request, HttpServletResponse response) throws BaseException{
		ResponseData responseData=new ResponseData();
		String export_id=request.getParameter("id");
		boolean result = dataExportService.download(export_id,request,response);
		if(result){
			responseData.setStatus(Constants.SUCCESS);
			responseData.setMsg("下载成功");
		}else{
			responseData.setStatus(Constants.ERROR);
			responseData.setMsg("下载失败");
		}	
		return  responseData;
	}

后端Service

public boolean download(String id, HttpServletRequest request, HttpServletResponse response) {
		
		String sql = "select file_path from data_export where id= '" + export_id + "'";
		String path = executeSql.selectStringValue(sql);
		
		OutputStream out = null;
        InputStream in = null;
        
        boolean result = false;
		try {
			File file = new File(path);
			//3.设置content-disposition响应头控制浏览器以下载的形式打开文件   前台使用windos.open方式下载
			response.setContentType("application/force-download");//应用程序强制下载
	        //下载使用的方法    最后是下载文件名  还有文件类型
			response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));
		    //开始下载
			// 读取要下载的文件,保存到文件输入流
	        in = new FileInputStream(path);
	        // 创建输出流
	        out = response.getOutputStream();
	        // 创建缓冲区
	        byte buffer[] = new byte[1024];
	        int len = 0;
	        //循环将输入流中的内容读取到缓冲区当中
	        while((len = in.read(buffer)) > 0){
	        	out.write(buffer, 0, len);
	        }
	        in.close();
	        out.close();
	        result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
            if(out != null){
            	try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        }
		
		return result;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值