我正在嘗試使用以下代碼在單擊時呼叫 REST GET API href。我需要在 HTTP GET 請求中發送我的自定義標頭。我希望 GET API 回傳的 pdf 檔案在href單擊時在瀏覽器的新選項卡中打開,而原始頁面保持在其選項卡中。
當我使用下面的代碼時,它會在新選項卡中打開相同的頁面 URL。當我查看在瀏覽器的 Javascript 控制臺下進行的網路呼叫時,它確實表明 API 是使用所需的標頭呼叫的。但是瀏覽器本身并沒有顯示。
<!DOCTYPE html>
<html>
<head>
<title> A jQuery click href </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#click_href').click(function() {
$.ajax({
url: 'http://myserver:8080/path/download?a=A&b=B&filename=file.pdf',
type: 'GET',
dataType: 'pdf',
beforeSend: function (xhr) {
xhr.setRequestHeader('CLIENT_ID', 'WEB_APP');
},
success: function (response) {
}
})
});
});
</script>
</head>
<body>
<h1> Demonstration for jQuery click href </h1>
<a href="#" id="click_href" target="_blank">Test by Curious Brain</a>
</body>
</html>
更新
這就是 Spring Boot REST 控制器回傳 PDF 的方式。如果我在瀏覽器視窗中嘗試直接下載 URL,則 PDF 會顯示在瀏覽器中。
@CrossOrigin
@RequestMapping(path = "/download", method = RequestMethod.GET, produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<InputStreamResource> download(
@RequestParam("a") String a,
@RequestParam("b") String b,
@RequestParam("filename") String fileName) throws IOException {
FileSystemResource pdfFile = new FileSystemResource(reportBaseDir "/" a "/" b "/" fileName);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_PDF_VALUE));
headers.setAccessControlAllowMethods(Arrays.asList(HttpMethod.GET));
headers.setAccessControlAllowHeaders(Arrays.asList("Content-Type"));
headers.setContentDisposition(ContentDisposition.builder("inline").filename(fileName).build());
headers.setCacheControl("no-cache, no-store, must-revalidate");
headers.setPragma("no-cache");
headers.setExpires(0L);
headers.setContentLength(pdfFile.contentLength());
return new ResponseEntity<InputStreamResource>(
new InputStreamResource(pdfFile.getInputStream()), headers, HttpStatus.OK);
}
根據下面給出的回復,我將我的 HTML 代碼更新為:
<!DOCTYPE html>
<html>
<head>
<title> A jQuery click href </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#click_href').click(function(e) {
e.preventDefault();
$.ajax({
url: 'http://myserver:8080/path/download?a=A&b=B&filename=file.pdf',
type: 'GET',
dataType: 'pdf',
beforeSend: function (xhr) {
xhr.setRequestHeader('CLIENT_ID', 'WEB_APP');
},
success: function (response) {
window.open("data:application/pdf," escape(response), '_blank');
}
})
});
});
</script>
</head>
<body>
<h1> Demonstration for jQuery click href </h1>
<a href="#" id="click_href">Test by Curious Brain</a>
</body>
</html>
即使這樣,我也可以看到對下載 URL 進行了呼叫,但沒有任何反應。單擊href鏈接時,我希望pdf檔案顯示在瀏覽器的新選項卡中。
來自瀏覽器的 Javascript 控制臺的網路跟蹤:
Summary
URL: http://myserver:8080/path/download?a=A&b=B&filename=file.pdf
Status: 200
Source: Network
Address: <some ip>:8080
Initiator:
jquery.min.js:2:82618
Request
GET /path/download HTTP/1.1
Accept: */*
Origin: null
Accept-Encoding: gzip, deflate
Host: myserver:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
CLIENT_ID: WEB_APP
Response
HTTP/1.1 200
Access-Control-Allow-Origin: *
Content-Type: application/pdf
Pragma: no-cache
Content-Disposition: inline; filename="file.pdf"
Keep-Alive: timeout=60
Access-Control-Allow-Methods: GET
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Access-Control-Allow-Headers: Content-Type
Cache-Control: no-cache, no-store, must-revalidate
Date: Thu, 13 Jan 2022 21:19:02 GMT
Content-Length: 387717
Connection: keep-alive
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Query String Parameters
a: A
b: B
filename: file.pdf
更新 2:
這是我能做到的最接近的。但這只會下載檔案。我試過window.open(…)了,但沒有在瀏覽器中打開檔案。
<!DOCTYPE html>
<html>
<head>
<title> A jQuery click href </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#click_href').click(function(e) {
e.preventDefault();
$.ajax({
//cache: false,
type: 'GET',
url: 'http:/myserver:8080/path/download?a=A&b=B&filename=file.pdf',
//contentType: false,
//processData: false,
data: 'native',
beforeSend: function (xhr) {
xhr.setRequestHeader('CLIENT_ID', 'WEB_APP');
},
xhrFields: {
responseType: 'blob'
},
success: function (response, status, xhr) {
var filename = '';
var disposition = xhr.getResponseHeader('Content-Disposition');
alert(disposition);
if (disposition) {
filename = disposition.split('"')[1];
alert(filename);
}
var linkelem = document.createElement('a');
var blob = new Blob([response], { type: 'application/octet-stream' });
var downloadUrl = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.target = "_blank";
//window.open(a);
a.click();
}
});
});
});
</script>
</head>
<body>
<h1> Demonstration for jQuery click href </h1>
<a href="#" id="click_href">Test by Curious Brain</a>
</body>
</html>
uj5u.com熱心網友回復:
瀏覽器正在新視窗中打開當前頁面,因為這就是鏈接的作用。
href="#"意思是“當前頁面的頂部”,target="_blank"意思是“在新視窗或標簽中”。
JavaScript 沒有呼叫preventDefault事件物件,因此不會阻止該行為。
Ajax 請求是一個完全獨立的 HTTP 請求,您在單擊鏈接時運行它。
它發出 HTTP 請求。
資料回傳給 JS。
success函式運行。
資料被傳遞到response變數中。
然后你……什么都沒有。
如果您想對來自 Ajax 請求的資料做一些事情,那么您必須實際做一些事情。
或許類似于這個問題的答案。
uj5u.com熱心網友回復:
不確定您的 API 呼叫會回傳什么回應,如果它回傳 pdf 檔案路徑,那么您可以簡單地使用 window.open();
<script>
$(document).ready(function() {
$('#click_href').click(function(e) {
e.preventDefault(); // this is to stop your page from reloading
$.ajax({
url: 'http://myserver:8080/path/download?a=A&b=B&filename=file.pdf',
type: 'GET',
dataType: 'pdf',
beforeSend: function (xhr) {
xhr.setRequestHeader('CLIENT_ID', 'WEB_APP');
},
success: function (response) {
// If your response if url then you can use
window.open(response, '_blank');
// IF your response is base64 PDF data then you can use something like
window.open("data:application/pdf," escape(response), '_blank');
}
})
});
});
</script>
您還需要從原始 a 標簽中洗掉 target="_blank"
uj5u.com熱心網友回復:
使用以下標記應該可以滿足您的需求,而無需任何額外的 JavaScript:
<a href="http://myserver:8080/path/download?a=A&b=B&filename=file.pdf"
target="_blank">Open pdf</a>
潛在檢查,對于其他有同樣問題的人:
Content-Disposition回應頭存在并設定為inline(在瀏覽器中打開檔案)和attachment(將檔案保存在磁盤上)。??- 瀏覽器能夠打開檔案型別(如果不能打開,它會下載檔案)??
Content-Type回應頭對于檔案型別應該是正確的。??- 檔案 URL 正確(包括協議)??
- (如果適用):該特定檔案型別的任何瀏覽器設定(本機或通過擴展)。如果是 PDF:
chrome://settings/content/pdfDocuments?
在您的情況下,上述所有內容都是正確的,除了最后一個,我不知道。但是,您是說.pdf如果您直接訪問鏈接,則可以在瀏覽器中打開,這意味著您可能選擇了“在 Chrome 中打開 PDF”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/410625.html
標籤:
上一篇:導航到特定單元格
