ssm實現視訊的上傳與播放
阿新 • • 發佈:2019-01-03
實現的功能:
1:實現視訊的上傳與播放。
2:使用shiro框架進行登入註冊。
3:視訊分頁展示在頁面上。
4:視訊簡介
5:視訊評論
6:發表評論
簡單介紹一下大概實現的思路:
首先主要的功能就是實現視訊的上傳與播放,那麼我們就需要一個視訊上傳的介面,選擇視訊進行上傳,那麼上傳到哪兒呢?
這裡我們有多重選擇,第一:我們可以將視訊轉換格式存在我們tomcat伺服器裡面,然後在資料庫裡面存入tomcat中對應的檔案的路徑。第二:我們可以使用nginx來儲存我們的網頁的靜態資源。今天我就介紹上面一個簡單的。
對於視訊的簡介,評論,以及發表評論無非就是對資料庫中進行增刪改查。
那麼我們下面就來簡單的介紹一下核心程式碼。
視訊上傳:
@RequestMapping(value = "dofunction", method = RequestMethod.POST) public void handler(HttpServletRequest request, HttpServletResponse response, @RequestParam("myvideo") MultipartFile file) throws IOException { String message = ""; try { Video media = new Video(); // 解析資料 media.setName(request.getParameter("name")); media.setDescription(request.getParameter("description")); boolean flag = false; // 轉碼成功與否的標記 // 上傳檔案 ServletContext sctx = request.getServletContext(); // 獲得儲存檔案的路徑 String basePath = sctx.getRealPath("videos"); // 獲得檔名 String fileUrl = file.getOriginalFilename(); // 在某些作業系統上,item.getName()方法會返回檔案的完整名稱,即包括路徑 String fileType = fileUrl.substring(fileUrl.lastIndexOf(".")); // 擷取檔案格式 // 自定義方式產生檔名 String serialName = String.valueOf(System.currentTimeMillis()); // 待轉碼的檔案 File uploadFile = new File(basePath + "/temp/" + serialName + fileType); // 儲存檔案 Streams.copy(file.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true); // 判斷檔案的大小 if (file.getSize() > 500 * 1024 * 1024) { message = "上傳失敗!您上傳的檔案太大,系統允許最大檔案500M"; } String codcFilePath = basePath + "/" + serialName + ".flv"; // 設定轉換為flv格式後文件的儲存路徑 String mediaPicPath = basePath + "/images" + File.separator + serialName + ".jpg"; // 設定上傳視訊截圖的儲存路徑 // 獲取配置的轉換工具(ffmpeg.exe)的存放路徑 String ffmpegPath = request.getServletContext().getRealPath("/tools/ffmpeg.exe"); media.setAddress("videos/" + serialName + ".flv"); media.setPicture("videos/images/" + serialName + ".jpg"); media.setUptime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()))); // 轉碼 flag = serviceFactory.getMediaService().executeCodecs(ffmpegPath, uploadFile.getAbsolutePath(), codcFilePath, mediaPicPath); if (flag) { // 轉碼成功,向資料表中新增該視訊資訊 serviceFactory.getMediaService().saveMedia(media); message="上傳成功"; } request.setAttribute("message", message); } catch (Exception e) { e.printStackTrace(); } MyWebPrinter.print(response,"<script>alert('"+message+"');window.location.href='indexing.cphtml';</script>"); }
視訊播放:
@RequestMapping("play") public String play(int id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idstr = id + ""; int mediaId = -1; Video media = null; if (null != idstr) { mediaId = Integer.parseInt(idstr); } try { media = serviceFactory.getMediaService().queryMediaById(mediaId); System.out.println(media.toString()); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("media", media); return "video-detail"; }
使用者使用shiro安全框架進行登入:
public class ShiroRealm extends AuthorizingRealm{
@Autowired
UserService userService;
protected AuthenticationInfo doGetAuthenticationInfo
(AuthenticationToken authenticationToken) throws AuthenticationException {
//此處的authenticationToken和controller中的UsernamePasswordToken是同一個,是controller中傳過來的
//System.out.println("doGetAuthenticationInfo " + authenticationToken.hashCode());
//1. 把 AuthenticationToken 轉換為 UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
//2. 從 UsernamePasswordToken 中來獲取 username
String username = upToken.getUsername();
//3. 呼叫資料庫的方法, 從資料庫中查詢 username 對應的使用者記錄(登入名和密碼)
//System.out.println("從資料庫中獲取 username: " + username + " 所對應的使用者資訊.");
User user = userService.findUserByEmail(username);
System.out.println(user.getEmail() + ", " + user.getPassword());
//4. 若使用者不存在, 則可以丟擲 UnknownAccountException 異常
// if("unknown".equals(username)){
// throw new UnknownAccountException("使用者不存在!");
// }
//5. 根據使用者資訊的情況, 決定是否需要丟擲其他的 AuthenticationException 異常
// if("monster".equals(username)){
// throw new LockedAccountException("使用者被鎖定");
// }
//6. 根據使用者的情況來構建 AuthenticationInfo物件並返回 通常用的實現類為: SimpleAuthenticationInfo
//以下資訊是從資料庫中獲取的.
//(1). principal : 認證的實體資訊 可以是 username 也可以是資料表對應的使用者的實體類物件
Object principal = username;
//(2). credentials : 密碼.
Object credentials = null;
if(user.getEmail().equals(username)){
credentials = user.getPassword();
}
//(3). realmName : 當前realm物件的name 呼叫父類的getName()方法即可
String realmName = getName();
//(4). salt : 鹽值 這裡用username作為鹽值 因為使用者名稱是唯一的
ByteSource salt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = null;
info = new SimpleAuthenticationInfo(principal,credentials,salt,realmName);
return info;
}
//測試獲取加密後的密碼 本例原密碼123456,加密2次
public static void main(String[] args) {
String hashAlgorithmName = "MD5";
Object credentials = "123456";
//Object salt = ByteSource.Util.bytes("[email protected]");//9be0a8423bbe47b9ab62b964d0e5b434
Object salt = ByteSource.Util.bytes("[email protected]");//9c377556e3611b4e4fe3d844f1a7135a
int hashIterations = 2;
//將一個字串進行MD5加密
Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(result);
}
//授權會被shiro回撥的方法
protected AuthorizationInfo doGetAuthorizationInfo
(PrincipalCollection principalCollection) {
//1. 從 PrincipalCollection 中來獲取登入使用者的資訊
// 注意如果是多realm,獲取的principal也是有順序的
Object principal = principalCollection.getPrimaryPrincipal();
//2. 利用登入的使用者的資訊來查使用者當前使用者的角色或許可權(可能需要查詢資料庫)
User_Role user_role = userService.findUserRoleByEmail((String) principal);
System.out.println("角色為:" + user_role.getRole_name());
Set<String> roles = new HashSet<String>();
roles.add("user");//給所有使用者新增user許可權
if(user_role.getRole_name().equals("admin")){
roles.add(user_role.getRole_name());//如果使用者的角色是admin,再新增一個admin許可權
}
//3. 建立 SimpleAuthorizationInfo, 並設定其 roles 屬性.
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
//4. 返回 SimpleAuthorizationInfo 物件.
return info;
}
頁面展示:
實現的過程,controller呼叫service中的方法,將結果呈現給在jsp頁面上,然後service層呼叫dao層中的對資料庫操作的方法。
注:視訊上傳是將視訊上傳到tomcat伺服器上面,當伺服器處於開著的狀態可以進行視訊的播放,當伺服器
關掉之後視訊將清空,如果tomcat設定的是關閉之後,將清空tomcat中的快取,就會出現在mysql資料庫中的儲存的視訊地址將失效,當然如果上傳的視訊儲存在專案根路徑下,那麼就不會出現這種情況。
專案原始碼,需要的私聊。本人小白,如有錯誤,請指正。