思路:
上傳:<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標簽就顯示了視頻,
效果如下(我做的手機端的,所以比較小)