下載文件到默認瀏覽器路徑
在controller接口入參直接傳HttpServletResponse response,然后設置文件名稱(fileName)和需要下載的文件類型(contentType),inputStream是要下載的文件流,無論是網絡文件還是存儲在阿里OOS或者騰訊COS靜態存儲服務中的文件,都可以轉化成InputStream的形式。
@GetMapping("/download")
public void download(HttpServletResponse response) {
return this.downloadFile(response);
}
public void downloadFile(HttpServletResponse response, InputStream inputStream, String fileName, String contentType) {
try (BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
//通知瀏覽器以附件形式下載
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
//文件輸出格式
response.setContentType(contentType);
byte[] car = new byte[1024];
int len;
while ((len = inputStream.read(car)) != -1) {
out.write(car, 0, len);
}
} catch (IOException e) {
log.error("Method:downloadFile,ErrorMsg:{}", e.getMessage());
}
}
啟動本地服務,把該接口鏈接url復制在瀏覽器上,點擊回車,就可以看到下載效果了。
如果在postman上測試,則需要在以下界面點下載按鈕:
Selenium修改瀏覽器默認下載路徑
代碼實現 java + selenium修改瀏覽器默認下載路徑方法
// 1.設置驅動路徑(驅動在 target 文件夾中)
System.setProperty("webdriver.chrome.driver", this.getClass().getResource("/").getPath() + "drivers/chromedriver.exe");
// 2.新的下載地址為桌面(可以弄成某個文件夾路徑而不要直接弄成死的靜態路徑)
String downloadPath = "C:\\Users\\XXX\\Desktop";
// 3.HashMap 中保存下載地址信息
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("download.default_directory", downloadPath);
// 4.ChromeOptions 中設置下載路徑信息,需要傳入保存有下載路徑的 HashMap
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", hashMap);
// 依據 ChromeOptions 來產生 DesiredCapbilities,這時 DesiredCapbilities 就也具備了下載路徑的信息了
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
// 5.依據 ChromeOptions 產生驅動,此時的 driver 已經具備了新的下載路徑的
WebDriver driver = new ChromeDriver(desiredCapabilities );
以上方法親測有效,僅為個人經驗,希望能給大家一個參考,也希望大家多多支持html5模板網。
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!