瀏覽器安全策略禁止 JavaScript 直接讀取任意遠端檔案(同源策略)。Firefox 不支援 ActiveXObject,IE 需降低安全等級才能嘗試,均不推薦。
// Spring MVC 範例
@GetMapping("/check-file")
public ResponseEntity<Boolean> check(@RequestParam String url) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("HEAD");
conn.setConnectTimeout(3000);
return ResponseEntity.ok(conn.getResponseCode() == 200);
} catch (Exception e) {
return ResponseEntity.ok(false);
}
}fetch('/check-file?url=' + encodeURIComponent(targetUrl))
.then(r => r.json())
.then(exists => console.log('檔案存在:', exists));new Image().src = url 監聽 onload/onerror,但無法區分 404 與跨域錯誤。永遠在伺服器端做檔案存在性檢查,前端僅負責發起請求並展示結果,確保安全與跨瀏覽器相容。