java實現下載文件到默認瀏覽器路徑
更新時間:2022年05月20日 09:03:10 作者:我們都愛松松吧
這篇文章主要介紹了java實現下載文件到默認瀏覽器路徑,具有很好的參考價值,希望對的大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
下載文件到默認瀏覽器路徑
在controller接口入參直接傳HttpServletResponse response,然后設置文件名稱(fileName)和需要下載的文件類型(contentType),inputStream是要下載的文件流,無論是網絡文件還是存儲在阿里OOS或者騰訊COS靜態(tài)存儲服務中的文件,都可以轉化成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.新的下載地址為桌面(可以弄成某個文件夾路徑而不要直接弄成死的靜態(tài)路徑)
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 );
以上方法親測有效,僅為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java,android,MD5加密算法的實現代碼(16位,32位)
下面小編就為大家?guī)硪黄猨ava,android,MD5加密算法的實現代碼(16位,32位)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09

