本期内容总结:
在做后端开发的过程中,经常会处理到将视频或者图片返回给前端。下面将封装一种可以简单的方法,前端只需要拼接接口地址+地址链接,即可播放下载。文章来源地址https://www.toymoban.com/news/detail-601918.html
@GetMapping(value="/videoOrImagePlay")
@Slf4j
public void videoOrImagePlay(HttpServletRequest request,HttpServletResponse response,@RequestParam("path")String path){
InputStream in = null;
ServletOutputStream out = null;
try{
//文件后缀名校验
String fileSuffix = path.subString(path.lastIndexOf(".") + 1);//文件后缀
fileSuffix = fileSuffix.toLowerCase();
//支持的文件后缀名白名单
String[] suffixWhiteList = {"png","jpeg","jpg","gif","ico","pdf","zip","mp3","mp4","flv"};
if(!Arrays.asList(suffixWhiteList).contains(fileSuffix.toLowerCase())){
logger.error(unSupport fileType!);
return;
}
//路径不能包含..
if (path.contains("..")) {
logger.error(error play path!);
return;
}
File file = new file(path);
int fSize = Integer.parseInt(String.valueOf(file.length()));
//拼接响应类型参数值:图片
StringBuilder type = new StringBuilder();
String typeStr = type.append("image/").append(fileSuffix).toString();
//图片白名单
String[] suffixImageList = {"png","jpeg","jpg","gif","ico"};
//视频白名单
String[] suffixVideoList = {"mp3","mp4","flv"};
if ("flv".equals(fileSuffix)){
response.setContentType("flv-application/octet-stream");
} else if(Arrays.asList(suffixImageList).contains(fileSuffix.toLowerCase())){
response.setContentType(typeStr);
} else{
response.setContentType("video/mp4");
}
response.setHeader("Accept-Ranges","bytes");
response.setHeader("Content-Disposition","attachment;fileName=" + path);
response.setHeader("Access-Control-Allow-Origin","*");
in = new FileInputStream(path);
long pos = 0;
if (null != request.getHeader("Range")){
//断点续传
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
try{
pos = Long.parseLong((request.getHeader("Range").replaceAll("bytes=","").split("-")[0]));
if (pos >= fSize){
pos = 0;
}
}catch (NumberFormatException e){
logger.error("NumberFormatException",e);
pos = 0;
}
}
out = response.getOutputStream();
String contentRange = new StringBuffer("bytes ").append(pos + "").append("-").append((fSize - 1) + "").append(fSize() + "").toString();
response.setHeader("Content-Range",contentRange);
//设置响应头Content-Length,防止浏览器请求数据量超过实际文件大小
response.setHeader("Content-Length","" + (fSize - pos));
in.skip(pos);
byte[] buffer = new byte[1024 * 10];
int length = 0;
while((length = in.read(buffer,0,buffer.length)) != -1){
out.write(buffer,0,length);
}
}catch (Exception e){
if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(ExceptionUtils.getMessage(e),"ClientAbortException")){
logger.error("ClientAbortException");
} else {
logger.error("Play FileStorage Failed",e);
}
}finally{
try{
if(null != out){
out.flush();
}
if(null != out){
out.close();
}
if(null != in){
in.close();
}
}catch(IOException e){
logger.error("IOException!",e);
}
}
}
文章来源:https://www.toymoban.com/news/detail-601918.html
到了这里,关于Java实现视频(mp4/flv/..)及图片(jpg/jpeg/png/..)给前端调用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!