下載文件到默認(rèn)瀏覽器路徑
在controller接口入?yún)⒅苯觽鱄ttpServletResponse response,然后設(shè)置文件名稱(chēng)(fileName)和需要下載的文件類(lèi)型(contentType),inputStream是要下載的文件流,無(wú)論是網(wǎng)絡(luò)文件還是存儲(chǔ)在阿里OOS或者騰訊COS靜態(tài)存儲(chǔ)服務(wù)中的文件,都可以轉(zhuǎn)化成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());
}
}
啟動(dòng)本地服務(wù),把該接口鏈接url復(fù)制在瀏覽器上,點(diǎn)擊回車(chē),就可以看到下載效果了。
如果在postman上測(cè)試,則需要在以下界面點(diǎn)下載按鈕:
Selenium修改瀏覽器默認(rèn)下載路徑
代碼實(shí)現(xiàn) java + selenium修改瀏覽器默認(rèn)下載路徑方法
// 1.設(shè)置驅(qū)動(dòng)路徑(驅(qū)動(dòng)在 target 文件夾中)
System.setProperty("webdriver.chrome.driver", this.getClass().getResource("/").getPath() + "drivers/chromedriver.exe");
// 2.新的下載地址為桌面(可以弄成某個(gè)文件夾路徑而不要直接弄成死的靜態(tài)路徑)
String downloadPath = "C:\\Users\\XXX\\Desktop";
// 3.HashMap 中保存下載地址信息
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("download.default_directory", downloadPath);
// 4.ChromeOptions 中設(shè)置下載路徑信息,需要傳入保存有下載路徑的 HashMap
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("prefs", hashMap);
// 依據(jù) ChromeOptions 來(lái)產(chǎn)生 DesiredCapbilities,這時(shí) DesiredCapbilities 就也具備了下載路徑的信息了
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
// 5.依據(jù) ChromeOptions 產(chǎn)生驅(qū)動(dòng),此時(shí)的 driver 已經(jīng)具備了新的下載路徑的
WebDriver driver = new ChromeDriver(desiredCapabilities );
以上方法親測(cè)有效,僅為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持html5模板網(wǎng)。
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!