App下載

ssm如何實現(xiàn)視頻的上傳和播放 詳細代碼解析

內(nèi)地十八線女明星 2021-08-13 14:40:29 瀏覽數(shù) (3176)
反饋

本篇文章主要介紹了如何使用SSM實現(xiàn)視頻的上傳以及播放的效果,正在學習SSM框架知識的小伙伴,本篇文章很有學習參考的價值,以下是詳情內(nèi)容。

實現(xiàn)的功能:

1:實現(xiàn)視頻的上傳與播放。

2:使用shiro框架進行登錄注冊。

3:視頻分頁展示在頁面上。

4:視頻簡介

5:視頻評論

6:發(fā)表評論

簡單介紹一下大概實現(xiàn)的思路:

首先主要的功能就是實現(xiàn)視頻的上傳與播放,那么我們就需要一個視頻上傳的界面,選擇視頻進行上傳,那么上傳到哪兒呢?

這里我們有多重選擇,第一:我們可以將視頻轉(zhuǎn)換格式存在我們tomcat服務(wù)器里面,然后在數(shù)據(jù)庫里面存入tomcat中對應(yīng)的文件的路徑。第二:我們可以使用nginx來存儲我們的網(wǎng)頁的靜態(tài)資源。今天我就介紹上面一個簡單的。

對于視頻的簡介,評論,以及發(fā)表評論無非就是對數(shù)據(jù)庫中進行增刪改查。

那么我們下面就來簡單的介紹一下核心代碼。

視頻上傳:

@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();
            // 解析數(shù)據(jù)
            media.setName(request.getParameter("name"));
            media.setDescription(request.getParameter("description"));
            boolean flag = false; // 轉(zhuǎn)碼成功與否的標記
            // 上傳文件
            ServletContext sctx = request.getServletContext();
            // 獲得保存文件的路徑
            String basePath = sctx.getRealPath("videos");
            // 獲得文件名
            String fileUrl = file.getOriginalFilename();
            // 在某些操作系統(tǒng)上,item.getName()方法會返回文件的完整名稱,即包括路徑
            String fileType = fileUrl.substring(fileUrl.lastIndexOf(".")); // 截取文件格式
            // 自定義方式產(chǎn)生文件名
            String serialName = String.valueOf(System.currentTimeMillis());
            // 待轉(zhuǎn)碼的文件
            File uploadFile = new File(basePath + "/temp/" + serialName + fileType);
 
            // 保存文件
            Streams.copy(file.getInputStream(),new FileOutputStream(uploadFile.getAbsolutePath()),true);
            // 判斷文件的大小
            if (file.getSize() > 500 * 1024 * 1024) {
                message = "上傳失??!您上傳的文件太大,系統(tǒng)允許最大文件500M";
            }
            String codcFilePath = basePath + "/" + serialName + ".flv"; // 設(shè)置轉(zhuǎn)換為flv格式后文件的保存路徑
            String mediaPicPath = basePath + "/images" + File.separator + serialName + ".jpg"; // 設(shè)置上傳視頻截圖的保存路徑
 
            // 獲取配置的轉(zhuǎn)換工具(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())));
            // 轉(zhuǎn)碼
            flag = serviceFactory.getMediaService().executeCodecs(ffmpegPath, uploadFile.getAbsolutePath(),
                    codcFilePath, mediaPicPath);
 
            if (flag) {
                // 轉(zhuǎn)碼成功,向數(shù)據(jù)表中添加該視頻信息
                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 轉(zhuǎn)換為 UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
 
        //2. 從 UsernamePasswordToken 中來獲取 username
        String username = upToken.getUsername();
 
        //3. 調(diào)用數(shù)據(jù)庫的方法, 從數(shù)據(jù)庫中查詢 username 對應(yīng)的用戶記錄(登錄名和密碼)
        //System.out.println("從數(shù)據(jù)庫中獲取 username: " + username + " 所對應(yīng)的用戶信息.");
        User user = userService.findUserByEmail(username);
        System.out.println(user.getEmail() + ", " + user.getPassword());
 
        //4. 若用戶不存在, 則可以拋出 UnknownAccountException 異常
//        if("unknown".equals(username)){
//            throw new UnknownAccountException("用戶不存在!");
//        }
 
        //5. 根據(jù)用戶信息的情況, 決定是否需要拋出其他的 AuthenticationException 異常
//        if("monster".equals(username)){
//            throw new LockedAccountException("用戶被鎖定");
//        }
 
        //6. 根據(jù)用戶的情況來構(gòu)建 AuthenticationInfo對象并返回 通常用的實現(xiàn)類為: SimpleAuthenticationInfo
        //以下信息是從數(shù)據(jù)庫中獲取的.
        //(1). principal : 認證的實體信息 可以是 username 也可以是數(shù)據(jù)表對應(yīng)的用戶的實體類對象
        Object principal = username;
        //(2). credentials : 密碼.
        Object credentials = null;
        if(user.getEmail().equals(username)){
            credentials = user.getPassword();
        }
        //(3). realmName : 當前realm對象的name 調(diào)用父類的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("lewy@9.com");//9be0a8423bbe47b9ab62b964d0e5b434
        Object salt = ByteSource.Util.bytes("muller@25.com");//9c377556e3611b4e4fe3d844f1a7135a
        int hashIterations = 2;
 
        //將一個字符串進行MD5加密
        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);
    }
 
    //授權(quán)會被shiro回調(diào)的方法
    protected AuthorizationInfo doGetAuthorizationInfo
               (PrincipalCollection principalCollection) {
        //1. 從 PrincipalCollection 中來獲取登錄用戶的信息
        //   注意如果是多realm,獲取的principal也是有順序的
        Object principal = principalCollection.getPrimaryPrincipal();
 
        //2. 利用登錄的用戶的信息來查用戶當前用戶的角色或權(quán)限(可能需要查詢數(shù)據(jù)庫)
        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權(quán)限
        if(user_role.getRole_name().equals("admin")){
            roles.add(user_role.getRole_name());//如果用戶的角色是admin,再添加一個admin權(quán)限
        }
 
        //3. 創(chuàng)建 SimpleAuthorizationInfo, 并設(shè)置其 roles 屬性.
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
 
        //4. 返回 SimpleAuthorizationInfo 對象.
        return info;
    }

頁面展示:

2021042109341412

2021042109341413

實現(xiàn)的過程,controller調(diào)用service中的方法,將結(jié)果呈現(xiàn)給在jsp頁面上,然后service層調(diào)用dao層中的對數(shù)據(jù)庫操作的方法。

注:視頻上傳是將視頻上傳到tomcat服務(wù)器上面,當服務(wù)器處于開著的狀態(tài)可以進行視頻的播放,當服務(wù)器
關(guān)掉之后視頻將清空,如果tomcat設(shè)置的是關(guān)閉之后,將清空tomcat中的緩存,就會出現(xiàn)在mysql數(shù)據(jù)庫中的存儲的視頻地址將失效,當然如果上傳的視頻保存在項目根路徑下,那么就不會出現(xiàn)這種情況。

以上內(nèi)容就是關(guān)于如何使用SSM來實現(xiàn)視頻上傳和播放的詳細過程的文章,想要了解更多關(guān)于SSM框架應(yīng)用的內(nèi)容,請多多關(guān)注W3Cschool相關(guān)文章,如果您覺得本篇文章還不錯,還希望可以多多支持!


0 人點贊