下载文件到默认浏览器路径
在controller接口入参直接传HttpServletResponse response,然后设置文件名称(fileName)和需要下载的文件类型(contentType),inputStream是要下载的文件流,无论是网络文件还是存储在阿里OOS或者腾讯COS静态存储服务中的文件,都可以转化成InputStream的形式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// 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 ); |
以上方法亲测有效,仅为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_37892675/article/details/109626982