1.将图片或视频的路径写入配置文件,并获取该配置
image:
path: /usr/local/image/
@Value("${image.path}")
private String imagePath;
2.图片返回方法
@ApiOperation(value = "查询图片", notes = "查询图片")
@GetMapping(value = "/getImage", produces = MediaType.IMAGE_PNG_VALUE)
@ResponseBody
public byte[] getImage(@Validated @RequestParam("imageName") String imageName, HttpServletResponse response) throws IOException {
File image = new File(imagePath + imageName);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(image);
int length = inputStream.available();
byte bytes[] = new byte[length];
response.setContentLength(length);
inputStream.read(bytes);
return bytes;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
3.视频返回方法
@ApiOperation(value = "视频播放", notes = "视频播放")
@GetMapping("play")
@ResponseBody
public void play(HttpServletRequest request, HttpServletResponse response, @Validated @RequestParam("videoUrl") String videoUrl) throws IOException {
response.reset();
File file = new File(imagePath + videoUrl);
long fileLength = file.length();
// 随机读文件
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
//获取从那个字节开始读取文件
String rangeString = request.getHeader("Range");
long range = 0;
if (StrUtil.isNotBlank(rangeString)) {
range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
}
//获取响应的输出流
OutputStream outputStream = response.getOutputStream();
//设置内容类型
response.setHeader("Content-Type", "video/mp4");
//返回码需要为206,代表只处理了部分请求,响应了部分数据
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
// 移动访问指针到指定位置
randomAccessFile.seek(range);
// 每次请求只返回1MB的视频流
byte[] bytes = new byte[1024 * 1024];
int len = randomAccessFile.read(bytes);
//设置此次相应返回的数据长度
response.setContentLength(len);
//设置此次相应返回的数据范围
response.setHeader("Content-Range", "bytes " + range + "-" + (fileLength - 1) + "/" + fileLength);
// 将这1MB的视频流响应给客户端
outputStream.write(bytes, 0, len);
outputStream.close();
randomAccessFile.close();
}