根据URL地址值获取附件并在浏览器下载保存

这段代码演示了如何从URL下载文件并将其作为附件提供给用户。它处理了不同浏览器的文件名编码问题,并通过ServletOutputStream将文件内容写入响应。
	/**
	 * 根据URL地址下载附件
	 * @param response
	 * @param fileUrl	文件路径
	 * @param nameOfPDF 自定义文件名
	 */
	public static void invoiceDownload(HttpServletResponse response, HttpServletRequest request,String fileUrl, String nameOfPDF) throws Exception{
		ServletOutputStream out = null;
		InputStream ips = null;
		URL oracle = null;
		oracle = new URL(fileUrl);
		HttpURLConnection uc = null;
		uc = (HttpURLConnection) oracle.openConnection();
		uc.setDoInput(true);
		uc.connect();
		//文件名
		String newFileName = fileName(fileUrl);
		ips =  uc.getInputStream();
		response.setContentType("multipart/form-data");
		//为文件重新设置名字
		String userAgent = request.getHeader("USER-AGENT");//获取浏览器版本
		if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
			nameOfPDF = URLEncoder.encode(nameOfPDF,"UTF8");
		}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
			nameOfPDF = new String(nameOfPDF.getBytes(), "ISO8859-1");
		}else{
			nameOfPDF = URLEncoder.encode(nameOfPDF,"UTF8");//其他浏览器
		}
		response.addHeader("Content-Disposition", "attachment; filename=\"" + nameOfPDF + ".pdf\"");
		out = response.getOutputStream();
		//读取文件流
		int len = 0;
		byte[] buffer = new byte[1024 * 10];
		while ((len = ips.read(buffer)) != -1){
			out.write(buffer,0,len);
		}
		out.flush();
		out.close();
		ips.close();
		return ;
	}
	/**
	 * 获取文件名字
	 * @param fileName
	 * @return
	 */
	private static String fileName(String fileName){
		if (StringUtils.isNotBlank(fileName)) {
			int offset = fileName.lastIndexOf("/");
			if (offset != -1 && offset != fileName.length() - 1) {
				String ext = fileName.substring(offset + 1);
				return ext.toLowerCase();
			}
		}
		return "";
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值