思路:

上传:<form>表单提交视频-->后台使用字节流保存到本地。
展示:<video>标签展示: src属性发送请求 --> 使用字节流将视频绑定到响应并返回。


这条思路适用于所有文件(包括图片,音频,视频,压缩包),下面只是视频的实例。

一上传

1.form表单提交视频

<form method="post" action="/manager/card/addMovie" enctype="multipart/form-data">
<input name="movie" type="file" MULTIPLE>
<input type="submit">
</form>

注意<input>使用 type="file" MULTIPLE 属性
<form>使用 enctype="multipart/form-data"


2.controller接收

@RequestMapping("/addMovie")
public String addMovie(MultipartFile movie){
..................;
}


3.使用字节流保存到本地

/**
*
* @param file
* @param path 保存的路径
* @param fileName 保存的文件名
*/
public static void saveFile(MultipartFile file, String path, String fileName) {

InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
byte[] bs = new byte[1024]; // 读取到的数据长度
int len; // 输出的文件流保存到本地文件
File tempFile = new File(path); // 保存到临时文件 1K的数据缓冲
if (!tempFile.exists()) {
tempFile.mkdirs();
}
outputStream = new FileOutputStream(tempFile.getPath() + File.separator + fileName);

while ((len = inputStream.read(bs)) != -1) { // 开始读取
outputStream.write(bs, 0, len);
}

} catch (Exception e) {
e.printStackTrace();
} finally { // 完毕,关闭所有链接
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


以上步骤视频就通过程序保存到电脑的指定位置了,一般我会新建一个视频类,先用uuid给视频重命名,视频类的路径是视频的名字,取的时候使用视频的名字去请求。

二 展示

1.video请求

    <video src="${file}/mp4+${mp4.paths}/${mp4.suffix}" controls="controls"
preload="auto">
</video>

注意:video要加controls="controls"才会有播放按钮显示,其他属性不一一介绍


2.使用字节流将视频绑定到响应并返回

@Controller
@RequestMapping("/file")
public class FileController {
/**
*
* @param response
* @param filePath 文件路径+名称
* @param suffix 文件的后缀
* @return
*/
@RequestMapping("/{filePath}/{suffix}")
public String getFile(HttpServletResponse response, @PathVariable String filePath, @PathVariable String suffix) {
FileInputStream fis = null;
ServletOutputStream outputStream = null;
int len = 0;
try {
File file = new File(FileUtils.getFileMainPath() + filePath + "." + suffix);
fis = new FileInputStream(file);
byte[] b = new byte[1024 * 2];
outputStream = response.getOutputStream();
while ((len = fis.read(b)) != -1) {
outputStream.write(b, 0, len);
}
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
fis = null;
outputStream = null;
}
}
return null;
}


}

等响应返回成功后video标签就显示了视频,

效果如下(我做的手机端的,所以比较小)