java通過http網(wǎng)絡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()); 之間有一些微小的區(qū)別。
URL url = new URL(fileUrl);:這種方式直接使用 URL 類的構(gòu)造函數(shù)創(chuàng)建一個 URL 對象。它假設 fileUrl 是一個合法的 URL 字符串,并不對其進行任何修改或編碼。如果 fileUrl 含有特殊字符或非法字符,可能會導致 MalformedURLException 異常。
URL url = new URL(new URI(fileUrl).toASCIIString());:這種方式先通過 URI 類創(chuàng)建一個 URI 對象,然后再將其轉(zhuǎn)換為 ASCII 字符串,最后使用 URL 類的構(gòu)造函數(shù)創(chuàng)建一個 URL 對象。這種方式會對 fileUrl 進行編碼,將其中的非 ASCII 字符轉(zhuǎn)換為 ASCII 編碼形式。這可以確保 URL 字符串的合法性。例如,使用這種方式可以正確處理包含中文或特殊字符的 URL。
總而言之,URL url = new URL(fileUrl); 直接創(chuàng)建 URL 對象,不對 URL 字符串進行編碼。而 URL url = new URL(new URI(fileUrl).toASCIIString()); 先通過 URI 對象將 URL 字符串編碼為 ASCII 形式,然后再創(chuàng)建 URL 對象。使用這種方式可以確保 URL 的合法性,尤其是處理包含非 ASCII 字符的 URL。
上面是本地保存到本地,以下是前端彈出保存框,可以選擇保存位置文章來源:http://www.zghlxwxcb.cn/news/detail-658473.html
@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"); // 創(chuàng)建臨時文件
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();
}*/
前端通過網(wǎng)絡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="";
//創(chuàng)建一個XMLHttpRequest對象
const xhr = new XMLHttpRequest()
//使用 xhr.open('GET', url) 打開一個GET請求,將URL作為請求的目標地址。
xhr.open('GET', url)
//指定返回的響應類型為Blob對象
xhr.responseType = 'blob'
//發(fā)送請求
xhr.send()
//發(fā)送請求后的回調(diào)
xhr.onload = function () {
//響應結(jié)果賦值給blob
const blob = xhr.response
//創(chuàng)建a標簽
const a = document.createElement('a')
//將下載文件的數(shù)據(jù)作為URL賦值給 <a> 標簽的 href 屬性
a.href = URL.createObjectURL(blob)
//下載文件名
a.download = 'test.pdf'
//點擊創(chuàng)建的a標簽
a.click()
}
}
</script>
<body>
<button onclick="btn()">aaaaa</button>
</body>
</html>
或文章來源地址http://www.zghlxwxcb.cn/news/detail-658473.html
function btn() {
var url = ("https://***/0974f0f.pdf");
//創(chuàng)建一個XMLHttpRequest對象,使用 `xhr.open('GET', url, true)` 打開一個GET請求,將URL作為請求的目標地址。
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // 也可以使用POST方式,根據(jù)接口
//將 `xhr.responseType` 設置為"blob",指定返回的響應類型為Blob對象
xhr.responseType = "blob";
// 當請求完成時觸發(fā)。在該回調(diào)函數(shù)中,首先檢查請求的狀態(tài)是否為200(即成功),如果是,則繼續(xù)處理
xhr.onload = function() {
// 請求完成
if (this.status === 200) {
// 返回200,從響應中獲取Blob對象,并創(chuàng)建一個FileReader對象
var blob = this.response;
var reader = new FileReader();
//將Blob對象轉(zhuǎn)換為base64格式的數(shù)據(jù),以便將其放入 `<a>` 標簽的 `href` 屬性中
reader.readAsDataURL(blob);
//在 `reader.onload` 回調(diào)函數(shù)中,創(chuàng)建一個 `<a>` 標簽用于下載,設置下載屬性和鏈接的URL
reader.onload = function(e) {
// 轉(zhuǎn)換完成,創(chuàng)建一個a標簽用于下載
var a = document.createElement('a');
a.download = '123.pdf';
a.href = e.target.result;
$("body").append(a); // 修復firefox中無法觸發(fā)click
a.click();
$(a).remove();
}
}
};
// 發(fā)送ajax請求
xhr.send()
}
到了這里,關(guān)于java通過http網(wǎng)絡url下載文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!