通过网络url下载文件

java通过http网络url下载文件

    @Test
    public void test3() throws ParseException {
        String fileUrl = "http://*****/123.pdf";
        String savePath = "C:\\Users\\HHH\\Desktop\\文件\\123.pdf";

        try {
            URL url = new URL(fileUrl);
            InputStream inputStream = url.openStream();

            Path outputPath = Path.of(savePath);
            Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

            System.out.println("File downloaded successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

上面代码报错,修改URL url = new URL(fileUrl);,使用URL url = new URL(new URI(fileUrl).toASCIIString());

    @Test
    public void test3() throws ParseException {
        String fileUrl = "http://*****/123.pdf";
        String savePath = "C:\\Users\\HHH\\Desktop\\文件\\123.pdf";

        try {
            URL url = new URL(new URI(fileUrl).toASCIIString());
            InputStream inputStream = url.openStream();

            Path outputPath = Path.of(savePath);
            Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

原因:

URL url = new URL(fileUrl); 和 URL url = new URL(new URI(fileUrl).toASCIIString()); 之间有一些微小的区别。
URL url = new URL(fileUrl);:这种方式直接使用 URL 类的构造函数创建一个 URL 对象。它假设 fileUrl 是一个合法的 URL 字符串,并不对其进行任何修改或编码。如果 fileUrl 含有特殊字符或非法字符,可能会导致 MalformedURLException 异常。
URL url = new URL(new URI(fileUrl).toASCIIString());:这种方式先通过 URI 类创建一个 URI 对象,然后再将其转换为 ASCII 字符串,最后使用 URL 类的构造函数创建一个 URL 对象。这种方式会对 fileUrl 进行编码,将其中的非 ASCII 字符转换为 ASCII 编码形式。这可以确保 URL 字符串的合法性。例如,使用这种方式可以正确处理包含中文或特殊字符的 URL。
总而言之,URL url = new URL(fileUrl); 直接创建 URL 对象,不对 URL 字符串进行编码。而 URL url = new URL(new URI(fileUrl).toASCIIString()); 先通过 URI 对象将 URL 字符串编码为 ASCII 形式,然后再创建 URL 对象。使用这种方式可以确保 URL 的合法性,尤其是处理包含非 ASCII 字符的 URL。

上面是本地保存到本地,以下是前端弹出保存框,可以选择保存位置

    @RequestMapping("/download")
    public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            URL url = new URL(new URI("https://*****/asd.pdf").toASCIIString());
            InputStream inputStream = url.openStream();

            fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"); // 处理文件名中的空格和特殊字符

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            Path tempFile = Files.createTempFile("temp", ".pdf"); // 创建临时文件
            Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);

            Files.copy(tempFile, response.getOutputStream()); // 将临时文件写入响应输出流

            response.flushBuffer();
            tempFile.toFile().delete(); // 删除临时文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*        
		
		try {
            URL url = new URL("https://asdasd/asd.pdf");
            URLConnection conn = url.openConnection();
            String fileName = "123asd.pdf";

            response.setContentType(conn.getContentType());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            InputStream inputStream = conn.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

            Path tempFile = Files.createTempFile("temp", "");
            Files.copy(bufferedInputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);

            Files.copy(tempFile, response.getOutputStream());
            response.flushBuffer();

            tempFile.toFile().delete();
            bufferedInputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

前端通过网络url下载文件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>

		</style>
	</head>
	<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
	<script>
		function btn() {
			//要下载的文件的url地址
			var url="";
			//创建一个XMLHttpRequest对象
			const xhr = new XMLHttpRequest()
			//使用 xhr.open('GET', url) 打开一个GET请求,将URL作为请求的目标地址。 
			xhr.open('GET', url)
			//指定返回的响应类型为Blob对象
			xhr.responseType = 'blob'
			//发送请求
			xhr.send()
			//发送请求后的回调
			xhr.onload = function () {
				//响应结果赋值给blob
			  const blob = xhr.response
			  //创建a标签
			  const a = document.createElement('a')
			  //将下载文件的数据作为URL赋值给 <a> 标签的 href 属性
			  a.href = URL.createObjectURL(blob)
			  //下载文件名
			  a.download = 'test.pdf'
			  //点击创建的a标签
			  a.click()
			}
		}
	</script>
	<body>
		<button onclick="btn()">aaaaa</button>
	</body>
</html>

function btn() {
   var url = ("https://***/0974f0f.pdf");   
   //创建一个XMLHttpRequest对象,使用 `xhr.open('GET', url, true)` 打开一个GET请求,将URL作为请求的目标地址。
   var xhr = new XMLHttpRequest();
   xhr.open('GET', url, true); // 也可以使用POST方式,根据接口
   //将 `xhr.responseType` 设置为"blob",指定返回的响应类型为Blob对象
   xhr.responseType = "blob";
   // 当请求完成时触发。在该回调函数中,首先检查请求的状态是否为200(即成功),如果是,则继续处理
   xhr.onload = function() {
      // 请求完成
      if (this.status === 200) {
         // 返回200,从响应中获取Blob对象,并创建一个FileReader对象
         var blob = this.response;
         var reader = new FileReader();
         //将Blob对象转换为base64格式的数据,以便将其放入 `<a>` 标签的 `href` 属性中
         reader.readAsDataURL(blob); 
         //在 `reader.onload` 回调函数中,创建一个 `<a>` 标签用于下载,设置下载属性和链接的URL
         reader.onload = function(e) {
            // 转换完成,创建一个a标签用于下载
            var a = document.createElement('a');
            a.download = '123.pdf';
            a.href = e.target.result;
            $("body").append(a); // 修复firefox中无法触发click
            a.click();
            $(a).remove();
         }
      }
   };
   // 发送ajax请求
   xhr.send()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值