java视频上传与播放功能

参考:https://wenku.baidu.com/view/63fb1da364ce0508763231126edb6f1aff0071c7.html

此次上传播放功能采用eclipse+ssm+maven +spring2.5+tomcat8+jdk8

这个功能是有一定缺陷的,CKplayer播放视频需要H264  MP4格式的,所以需要格式转化,网盘上都有。

需要源码的百度网盘地址:

链接: https://pan.baidu.com/s/1GXA_VZVmZFyRxLqZZwrY0A

提取码: 16sq

2020年1月3日:今天重新做了一版idea+springboot+ftp(在我自己的服务器上的ftp)的文件上传和播放,如果没有FTP文件服务器,这个不行;

写的非常简单,给你们连接地址:

链接:https://pan.baidu.com/s/1NVLxa0yQ4_Txr72jxVv0Ug 
提取码:mm6k

 

FileEntity:

    private long fileId;

    /*****
     * 原文件名
     ***/
    
    private String titleOrig;

    /*****
     * 修改后文件名
     ***/
    
    private String titleAlter;

    /*****
     * 文件大小
     ***/
    
    private String size;

    /*****
     * 文件类型
     ***/
    
    private String type;

    /*****
     * 文件保存路径
     ***/
    
    private String path;

    /*****
     * 文件上传时间
     ***/
    
    private Timestamp uploadTime;

控制层:

@RequestMapping(value = "/upload")
@ResponseBody
public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile multipartFile,
HttpServletRequest request, ModelMap map) {
String message = "";
FileEntity entity = new FileEntity();
String logoPathDir=request.getParameter("shipin");
System.out.println("-------"+logoPathDir+"----------------------------------");
FileUploadTool fileUploadTool = new FileUploadTool();
try {
entity = fileUploadTool.createFile(logoPathDir,multipartFile, request);
if (entity != null) {
service.saveFile(entity);
message = "上传成功";
map.put("entity", entity);
map.put("result", message);
} else {
message = "上传失败";
map.put("result", message);
}


} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("/pages/views/result", map);
}


 

@RequestMapping(value = "/{id}/play")
@ResponseBody
public ModelAndView playVideo(@PathVariable("id") long id, ModelMap model) {


// CharterDto charterDto_ = charterFacade.getCharterById(id);
FileEntity entity = service.findByid(id);
model.put("entity", entity.getPath());
ModelAndView view = new ModelAndView("index", model);
return view;
}



 

@RequestMapping("/show")
@ResponseBody
public ModelAndView showList(HttpServletRequest request, ModelMap map) {
// 获取上传文件目录
String logoPathDir = "/video/";
String uploadFilePath =request.getSession().getServletContext().getRealPath(logoPathDir);
// 存储要下载的文件名
List fileNameMap = new ArrayList();
this.listFile(new File(uploadFilePath), fileNameMap);
map.put("list", fileNameMap);
return new ModelAndView("listFile", map);


}



 

/**
* @Description: 递归遍历指定目录下的所有文件
* @param file:即代表一个文件,也代表一个文件目录
* @param map:存储文件名的Map集合
*/
public void listFile(File file, List map) {
// 如果file代表的不是一个文件,而是一个目录
if (!file.isFile()) {
// 列出该目录下的所有文件和目录
File files[] = file.listFiles();
// 遍历files[]数组
for (File f : files) {
// 递归
listFile(f, map);
}
} else {
map.add(file.getName());
}
}


 

@RequestMapping(value = "/download")//下载
@ResponseBody
public void download(@RequestParam(value = "filename", required = false) String fileName,
HttpServletRequest request, ModelMap map, HttpServletResponse response) {
try {
fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// 获取上传文件目录
String logoPathDir = "/video/";
String fileSaveRootPath = request.getSession().getServletContext().getRealPath(logoPathDir);
// 文件路径
String fileDir = fileSaveRootPath + File.separator + fileName;
File file = new File(fileDir);
if (!file.exists()) {
System.out.println("下载的文件不存在");
return;
}
// 设置响应头,控制浏览器下载该文件
try {
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 读取要下载的文件,保存到文件输入流
FileInputStream in = null;
try {
in = new FileInputStream(fileDir);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 创建输出流
OutputStream out;
try {
out = response.getOutputStream();
// 创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
// 循环将输入流中的内容读取到缓冲区当中
while ((len = in.read(buffer)) > 0) {
// 输出缓冲区的内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
// 关闭文件输入流
in.close();
// 关闭输出流
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}

工具类:

package com.util;


import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;


import javax.servlet.http.HttpServletRequest;


import org.springframework.web.multipart.MultipartFile;


import com.model.sj.FileEntity;
//文件上传工具
public class FileUploadTool {


// 文件最大500M
private static long upload_maxsize = 5000 * 1024 * 1024;
// 文件允许格式
private static String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".xlsx", ".gif",
".png", ".jpg", ".jpeg", ".bmp", ".xls", ".mp4", ".flv", ".ppt", ".avi", ".mpg", ".wmv", ".3gp", ".mov",
".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb" };
// 允许转码的视频格式(ffmpeg)
private static String[] allowFLV = { ".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob" };
// 允许的视频转码格式(mencoder)
private static String[] allowAVI = { ".wmv9", ".rm", ".rmvb" };


public FileEntity createFile(String logoPathDir,MultipartFile multipartFile, HttpServletRequest request) {
FileEntity entity = new FileEntity();
boolean bflag = false;
String fileName = multipartFile.getOriginalFilename().toString();
System.out.println("文件全称:"+fileName+"~~~~~~~~~~~~~~");
// 判断文件不为空
if (multipartFile.getSize() != 0 && !multipartFile.isEmpty()) {
bflag = true;
// 判断文件大小
if (multipartFile.getSize() <= upload_maxsize) {
bflag = true;
// 文件类型判断
if (this.checkFileType(fileName)) {
bflag = true;
} else {
bflag = false;
System.out.println("文件类型不允许");
}
} else {
bflag = false;
System.out.println("文件大小超范围");
}
} else {
bflag = false;
System.out.println("文件为空");
}
if (bflag) {
//String logoPathDir = "/video/";
String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);
System.out.println("全路径不加项目名:"+logoRealPathDir+"*************************");
// 上传到本地磁盘
// String logoRealPathDir = "E:/upload";
File logoSaveFile = new File(logoRealPathDir);
if (!logoSaveFile.exists()) {
logoSaveFile.mkdirs();
}
String name = fileName.substring(0, fileName.lastIndexOf("."));
System.out.println("文件名称:" + name);
// 新的文件名
String newFileName = this.getName(name);
// 文件扩展名
String fileEnd = this.getFileExt(fileName);
// 绝对路径
String fileNamedirs = logoRealPathDir + File.separator + newFileName + fileEnd;
System.out.println("这是啥:fileEnd:"+fileEnd);
System.out.println("这是啥:File.separator:"+File.separator);
System.out.println("保存的绝对路径:" + fileNamedirs);
File filedirs = new File(fileNamedirs);
// 转入文件
try {
multipartFile.transferTo(filedirs);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 相对路径
entity.setType(fileEnd);
String fileDir = logoPathDir + newFileName + fileEnd;
StringBuilder builder = new StringBuilder(fileDir);
String finalFileDir = builder.substring(1);
// size存储为String
String size = this.getSize(filedirs);
// 源文件保存路径
String aviPath = filedirs.getAbsolutePath();
if (aviPath!=null) {

entity.setSize(size);
entity.setPath(finalFileDir);
entity.setTitleOrig(name);
entity.setTitleAlter(newFileName); 
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
entity.setUploadTime(timestamp);
return entity;
} 
} else {
return null;
}
return entity;


}


/**
* 文件类型判断
*
* @param fileName
* @return
*/
private boolean checkFileType(String fileName) {
Iterator type = Arrays.asList(allowFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.toLowerCase().endsWith(ext)) {
return true;
}
}


return false;
}


/**
* 视频类型判断(flv)
*
* @param fileName
* @return
*/
private boolean checkMediaType(String fileEnd) {
Iterator type = Arrays.asList(allowFLV).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileEnd.equals(ext)) {
return true;
}
}
return false;
}


/**
* 视频类型判断(AVI)
*
* @param fileName
* @return
*/
private boolean checkAVIType(String fileEnd) {
Iterator type = Arrays.asList(allowAVI).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileEnd.equals(ext)) {
return true;
}
}
return false;
}


/**
* 获取文件扩展名
*
* @return string
*/
private String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}


/**
* 依据原始文件名生成新文件名
* UUID:全局唯一标识符,由一个十六位的数字组成,由三部分组成:当前日期和时间、时钟序列、全局唯一的IEEE机器识别号
* @return string
*/
private String getName(String fileName) {
Random random = new Random();
return "" + random.nextInt(10000) + System.currentTimeMillis();
//return UUID.randomUUID().toString() + "_" + fileName;


}


/**
* 文件大小,返回kb.mb
* 
* @return
*/
private String getSize(File file) {
String size = "";
long fileLength = file.length();
DecimalFormat df = new DecimalFormat("#.00");
if (fileLength < 1024) {
size = df.format((double) fileLength) + "BT";
} else if (fileLength < 1048576) {
size = df.format((double) fileLength / 1024) + "KB";
} else if (fileLength < 1073741824) {
size = df.format((double) fileLength / 1048576) + "MB";
} else {
size = df.format((double) fileLength / 1073741824) + "GB";
}


return size;


}


}

JSP上传页面:

 

           
               
                   文件上传:                    上传地址:                
                                   
           
         

JSP显示页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>





上传视频结果


上传结果

${result}

文件名称 文件大小 文件类型 文件路径 上传时间 操作
${entity.titleOrig} ${entity.size} ${entity.type} ${entity.path} ${entity.uploadTime}

 

你可能感兴趣的:(java后台)