java 从网络Url中下载文件

Java知识分享(spring全家桶、面试突击)

每天进步一点点


为什么要写这篇文章呢?生产bug!!!
Beta环境下,点击:图片可以展示图片,文件直接下载
图片1

生产环境下,图片地址是公网,外网下没有访问权限,功能不正常。所以改用流的方式去获取网络资源。

下载文件

	/**
	 * @param contract
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/downLoadFile")
	public void downLoadFile(String contract, HttpServletResponse response) throws Exception {
		log.info("CreateZoneController downLoadFile contract:" + contract);
		
		try {
			//获取文件名
			String fileName = contract.substring(contract.lastIndexOf("/")+1);
			fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
			log.info("CreateZoneController downLoadFile fileName:" + fileName);
			
			long beginTime = System.currentTimeMillis();
			HttpFileDownLoad.downLoadFromUrl(contract, fileName, response);
			log.info("CreateZoneController downLoadFile success cosTime: {}", (System.currentTimeMillis()-beginTime));
		} catch (Exception e) {
			log.error("CreateZoneController downLoadFile" );
		}
	}

http文件下载

/**
 * http文件下载
 * 
 * @author zhoudoujun01
 * @date 2019年12月18日14:58:17
 */
public class HttpFileDownLoad {
	private static final Logger log = LogManager.getLogger(HttpFileDownLoad.class);

	/**
	 * 从网络Url中下载文件
	 * 
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void downLoadFromUrl(String urlStr, String fileName, HttpServletResponse response) throws IOException {
		InputStream inputStream = null;
		ServletOutputStream responOutPut = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置超时间为3秒
			conn.setConnectTimeout(3 * 1000);
			// 防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// conn.setRequestProperty("lfwywxqyh_token",toekn);
			
			// 得到输入流
			inputStream = conn.getInputStream();
			
			responOutPut = response.getOutputStream();
			
			// 设置下载文件头及文件名称
			response.setHeader("Content-Transfer-Encoding", "binary");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

			// 流写出
			byte[] buffer = new byte[1024 * 100];
			int i = 0;
			while ((i = inputStream.read(buffer)) > 0) {
				responOutPut.write(buffer, 0, i);
			}
			
			responOutPut.flush();
		} catch (Exception e) {
			log.error("HttpFileDownLoad downLoadFromUrl error: {}", e);
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
			if(responOutPut != null) {
				responOutPut.close();
			}
		}
	}
}

jsp页面

<a href="<%=basePath%>createZone/downLoadFile?contract=${zoneInfo.contract }" target="_blank" style="color:blue">图片1</a>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值