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

这段代码演示了如何从URL下载文件并将其作为附件提供给用户。它处理了不同浏览器的文件名编码问题,并通过ServletOutputStream将文件内容写入响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	/**
	 * 根据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 "";
	}

### 浏览器输入URL后直接触发文件下载的方法 当用户在浏览器中输入特定的URL来触发文件下载时,前端可以通过多种方式实现这一功能。一种常见的方式是通过设置HTTP响应头中的`Content-Disposition`属性为`attachment`,这会提示浏览器将接收到的内容视为附件立即启动下载过程[^1]。 对于具体的前端实现方法之一是在HTML文档内创建一个隐藏的链接元素(`<a>`标签),通过JavaScript动态修改其`href`属性指向目标文件的位置,模拟点击事件以触发下载行为: ```html <a id="downloadLink" style="display:none;"></a> <script type="text/javascript"> function downloadFile(url){ var link=document.getElementById('downloadLink'); link.href=url; link.download=''; // 可选参数,用于指定保存下来的文件名 document.body.appendChild(link); link.click(); document.body.removeChild(link); } </script> ``` 另一种更为现代的做法是利用Fetch API获取资源将Blob对象传递给新创建的对象URL,再借助之前提到过的隐式锚点完成操作: ```javascript async function fetchAndDownloadFile(fileUrl,filename){ try{ const response=await fetch(fileUrl); const blob=await response.blob(); let aTag=document.createElement('a'); aTag.style.display='none'; document.body.appendChild(aTag); const url=window.URL.createObjectURL(blob); aTag.href=url; aTag.download=filename; aTag.click(); window.URL.revokeObjectURL(url); document.body.removeChild(aTag); }catch(error){ console.error(`Error during fetching and downloading file:${error.message}`); } } ``` 上述两种方案均能在不依赖于任何第三方库的情况下有效工作,在实际应用开发中可根据具体需求选用合适的技术路径[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值