用戶想:前端讓用戶選資料夾 → 把路徑傳後端 → 後端直接寫文件到用戶本地路徑。**這在瀏覽器沙箱模型下根本不可能。**
<input type="file" webkitdirectory> 只能**讀**用戶選擇的文件,**不能**寫入指定路徑// 後端 Spring Boot 示例
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");
try (OutputStream os = response.getOutputStream()) {
Workbook wb = new XSSFWorkbook();
// 填充數據...
wb.write(os);
}
}
// 前端調用
window.location.href = '/api/export'; // 或 fetch + blob 下載
// 前端 fetch + ReadableStream
const response = await fetch('/api/export-large');
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let received = 0;
const chunks = [];
while (true) {
const {done, value} = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
updateProgress(received / contentLength);
}
const blob = new Blob(chunks);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'report.xlsx';
a.click();
URL.revokeObjectURL(url);
dialog.showSaveDialog + 後端本地寫入chrome.downloads.download 可指定 filename 建議名,但無法強制路徑FileSystemDirectoryHandle 寫入,**但後端無法直接用此句柄**
**後端生成二進制流 → HTTP 響應頭 Content-Disposition: attachment → 瀏覽器自動彈出下載/按用戶瀏覽器設置保存到默認下載目錄**,這是 Web 標準、跨平台、無兼容性問題的唯一正解。別嘗試突破沙箱,那是安全邊界。