远程下载pdf文件 java代码

最近在搞一个pdf下载 下载远程文件


先把代码跟大家共享一下,如果找到更好的代码,会更新的


public String DownLoad_fun() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String pid = request.getParameter("path");
//		String mid = request.getParameter("mid");
		String mid = pid.split(",")[1];
		Post_meta post_meta = new Post_meta();
		post_meta.setMeta_key("pdf_files");
		post_meta.setMeta_value(mid.trim());
		String str = postService.SelPostImg(post_meta);
		String path=str.split("#")[0].split("@")[1];
		System.out.println(path);
		logger.info("--------->"+path);
		try {
				URL url = new URL(path);
				Date date=new Date();
				int rand = (int) (Math.random() * 1000000);
				SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
				String filedisplay = str.split("#")[0].split("@")[2]+sdf.format(date)+rand+".pdf";// 下载文件时显示的文件保存名称
				String filenamedisplay = URLEncoder.encode(filedisplay, "UTF-8");
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setStatus(200);
				response.setContentType("application/pdf");
				response.addHeader("Content-Disposition", "attachment;filename=" + filenamedisplay);

				InputStream fileInputStream = url.openStream();
				OutputStream responseOutputStream = response.getOutputStream();
				int bytes;
				while ((bytes = fileInputStream.read()) != -1) {
					responseOutputStream.write(bytes);
				}
				fileInputStream.close();
				responseOutputStream.close();
				
		
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "download_fun";
	}


现在还是有错误,下载的功能是正常的,如果谁可以帮我找到错误可以留言哦!!



这个报错的问题已经解决了,就是吧最后那个

return "download_fun";
改为 return null 就可以了 因为已经吧reponse 各种流都给关闭了,这里再返回值就会报错。


如果要是通过ajax 实现的方法希望返回的时候都写 return null;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值