BrowserController.java
2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package cn.com.glsx.base.modules.controller;
import cn.com.glsx.admin.common.util.fileupload.FileConstants;
import cn.com.glsx.admin.common.util.fileupload.FileUploadServerData;
import cn.com.glsx.admin.common.util.fileupload.FileUploadUtil;
import com.glsx.plat.common.utils.SnowFlake;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.page.ElementHandle;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.ScreenshotOptions;
import com.ruiyun.jvppeteer.options.WaitForSelectorOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Base64;
@Slf4j
@RestController
@RequestMapping(value = "/browser")
public class BrowserController {
@Autowired
private Browser browser;
@GetMapping("/screenshot")
public R<String> screenshot(@RequestParam("url") String url, String filename, Integer quality) throws IOException, InterruptedException {
Page page = browser.newPage();
page.setDefaultTimeout(1000 * 6);
page.goTo(url, false);
//根据dom判断是否加载完
WaitForSelectorOptions waitForSelectorOptions = new WaitForSelectorOptions();
waitForSelectorOptions.setTimeout(1000 * 15);
waitForSelectorOptions.setVisible(Boolean.TRUE);
ElementHandle elementHandle = page.waitForSelector("testdom", waitForSelectorOptions);
ScreenshotOptions screenshotOptions = new ScreenshotOptions();
screenshotOptions.setType(MediaType.IMAGE_JPEG.getSubtype());
screenshotOptions.setQuality(quality != null ? quality : 70);
//设置截图范围
screenshotOptions.setFullPage(Boolean.TRUE);
if (StringUtils.isNullOrEmpty(filename)) {
filename = SnowFlake.nextSerialNumber();
}
screenshotOptions.setPath("E:\\" + filename + ".jpg");
String base64Str = page.screenshot(screenshotOptions);
byte[] buffer = Base64.getDecoder().decode(base64Str);
FileUploadServerData uploadServerData = FileUploadUtil.uploadToFileSystem(filename, buffer, FileConstants.JPG_TYPE);
return R.ok().data(uploadServerData.getSecureUrl());
}
}