App下載

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

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

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

實(shí)現(xiàn)的功能:

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

2:使用shiro框架進(jìn)行登錄注冊(cè)。

3:視頻分頁(yè)展示在頁(yè)面上。

4:視頻簡(jiǎn)介

5:視頻評(píng)論

6:發(fā)表評(píng)論

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

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

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

對(duì)于視頻的簡(jiǎn)介,評(píng)論,以及發(fā)表評(píng)論無(wú)非就是對(duì)數(shù)據(jù)庫(kù)中進(jìn)行增刪改查。

那么我們下面就來(lái)簡(jiǎn)單的介紹一下核心代碼。

視頻上傳:

@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)碼成功與否的標(biāo)記
            // 上傳文件
            ServletContext sctx = request.getServletContext();
            // 獲得保存文件的路徑
            String basePath = sctx.getRealPath("videos");
            // 獲得文件名
            String fileUrl = file.getOriginalFilename();
            // 在某些操作系統(tǒng)上,item.getName()方法會(huì)返回文件的完整名稱,即包括路徑
            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安全框架進(jìn)行登錄:

public class ShiroRealm extends AuthorizingRealm{
 
    @Autowired
    UserService userService;
 
    protected AuthenticationInfo doGetAuthenticationInfo
            (AuthenticationToken authenticationToken) throws AuthenticationException {
        //此處的authenticationToken和controller中的UsernamePasswordToken是同一個(gè),是controller中傳過(guò)來(lái)的
        //System.out.println("doGetAuthenticationInfo " + authenticationToken.hashCode());
 
        //1. 把 AuthenticationToken 轉(zhuǎn)換為 UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
 
        //2. 從 UsernamePasswordToken 中來(lái)獲取 username
        String username = upToken.getUsername();
 
        //3. 調(diào)用數(shù)據(jù)庫(kù)的方法, 從數(shù)據(jù)庫(kù)中查詢 username 對(duì)應(yīng)的用戶記錄(登錄名和密碼)
        //System.out.println("從數(shù)據(jù)庫(kù)中獲取 username: " + username + " 所對(duì)應(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ù)用戶的情況來(lái)構(gòu)建 AuthenticationInfo對(duì)象并返回 通常用的實(shí)現(xiàn)類為: SimpleAuthenticationInfo
        //以下信息是從數(shù)據(jù)庫(kù)中獲取的.
        //(1). principal : 認(rèn)證的實(shí)體信息 可以是 username 也可以是數(shù)據(jù)表對(duì)應(yīng)的用戶的實(shí)體類對(duì)象
        Object principal = username;
        //(2). credentials : 密碼.
        Object credentials = null;
        if(user.getEmail().equals(username)){
            credentials = user.getPassword();
        }
        //(3). realmName : 當(dāng)前realm對(duì)象的name 調(diào)用父類的getName()方法即可
        String realmName = getName();
        //(4). salt : 鹽值 這里用username作為鹽值 因?yàn)橛脩裘俏ㄒ坏?        ByteSource salt = ByteSource.Util.bytes(username);
 
        SimpleAuthenticationInfo info = null;
        info = new SimpleAuthenticationInfo(principal,credentials,salt,realmName);
 
        return info;
    }
 
    //測(cè)試獲取加密后的密碼 本例原密碼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;
 
        //將一個(gè)字符串進(jìn)行MD5加密
        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);
    }
 
    //授權(quán)會(huì)被shiro回調(diào)的方法
    protected AuthorizationInfo doGetAuthorizationInfo
               (PrincipalCollection principalCollection) {
        //1. 從 PrincipalCollection 中來(lái)獲取登錄用戶的信息
        //   注意如果是多realm,獲取的principal也是有順序的
        Object principal = principalCollection.getPrimaryPrincipal();
 
        //2. 利用登錄的用戶的信息來(lái)查用戶當(dāng)前用戶的角色或權(quán)限(可能需要查詢數(shù)據(jù)庫(kù))
        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,再添加一個(gè)admin權(quán)限
        }
 
        //3. 創(chuàng)建 SimpleAuthorizationInfo, 并設(shè)置其 roles 屬性.
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
 
        //4. 返回 SimpleAuthorizationInfo 對(duì)象.
        return info;
    }

頁(yè)面展示:

2021042109341412

2021042109341413

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

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

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


0 人點(diǎn)贊