springboot项目需要先做一个初始化操作,不然会抛异常
@SpringBootApplication
public class HttpApplication {
public static void main(String[] args) {
// 解决 java.awt.HeadlessException
System.setProperty("java.awt.headless","false");
SpringApplication.run(HttpApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
代码实现
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@Service
public class Test{
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/screenshot")
public void screenImgTask() throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
//获取系统临时缓存目录
String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String tempFilePath = System.getProperty("java.io.tmpdir") + fileName + ".png";
//生成一个临时文件
File file = new File(tempFilePath);
ImageIO.write(image, "png", file);
System.out.println("文件名称 -> " + file.getName());
//把临时文件转换成FileSystemResource
FileSystemResource resource = new FileSystemResource(file);
//创建请求头
HttpHeaders headers = new HttpHeaders();
//设置头格式
MediaType type = MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE);
headers.setContentType(type);
MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
//由于上传文件不能直接使用MultipartFile类型来进行上传,需要转换为FileSystemResource类型进行上传
bodyMap.add("multipartFile", resource);
bodyMap.add("screenshotId", "123");
bodyMap.add("width", image.getWidth());
bodyMap.add("high", image.getHeight());
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(bodyMap, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:8080/screenshot/save", HttpMethod.PUT, httpEntity, String.class);
//删除临时文件
try {
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(responseEntity.getBody());
}
}
controller层
/**
* 保存截屏记录和图片
*
* @param multipartFile 图片
* @param screenshotId 截屏ID
* @param width 图片宽度
* @param high 图片高度
* @return
*/
@RequestMapping("screenshot/save")
public ResultVo add(@RequestBody MultipartFile multipartFile, @RequestParam String screenshotId,
@RequestParam Integer width, @RequestParam Integer high) {
if (multipartFile == null) {
return ResultVo.error("图片不能为空");
}
return screenShotService.add(multipartFile, taskId, width, high);
}
service层
/**
* 保存截屏记录和图片
*
* @param multipartFile 图片
* @param screenshotId 截屏ID
* @param width 图片宽度
* @param high 图片高度
* @return
*/
@Override
public ResultVo add(MultipartFile multipartFile, String screenshotId, Integer width, Integer high) {
if (StringUtils.isNull(taskId)) {
return null;
}
ScreenshotEntity screenShotEntity = this.getById(screenshotId);
if (screenShotEntity == null) {
return ResultVo.error("该截屏记录不存在");
}
//图片宽(像素)
screenShotEntity.setScreenshotWidth(width);
//图片高(像素)
screenShotEntity.setScreenshotHeight(high);
//图片大小(字节)
screenShotEntity.setScreenshotSize(multipartFile.getSize());
//创建时间
screenShotEntity.setCreatedAt(new Date());
//修改时间
screenShotEntity.setUpdatedAt(new Date());
//根据路径,新建一个文件
String url = screenShotEntity.getScreenshotUrl() + multipartFile.getOriginalFilename();
File file = new File(url);
//判断文件目录是否存在
if (!file.getParentFile().exists()) {
//创建文件目录
file.getParentFile().mkdirs();
try {
//创建新文件
file.createNewFile();
} catch (IOException e) {
logger.error("文件 [{}] 创建失败", url);
e.printStackTrace();
}
}
//保存图片
try {
//将源文件内容转移到创建好的文件中
multipartFile.transferTo(file);
screenShotEntity.setScreenshotUrl(url);
//保存
boolean update = this.updateById(screenShotEntity);
if (!update) {
return ResultVo.error("修改截屏记录失败");
}
return ResultVo.ok();
} catch (IOException e) {
e.printStackTrace();
return ResultVo.error("保存截屏图片失败");
}
}