vue前端播放视频

javascript 复制代码
  <div style="display: flex; justify-content: center; align-items: center; height: 60vh; margin-top: 10vh;">
    <video ref="videoPlayer" controls style="width: auto; height: 100%;"></video>
  </div>
</template>

<script>
    export default {
        name: 'viewFDDetails',
        props: {
            tableData: {},
            id:String
        },
        data() {
            return {};
        },
        mounted() {},

        computed: {

        },
        methods: {
            viewVideo(row,type){
              console.log("row=",row);
              console.log("totalBatch=",row.totalBatch,"idNumber",row.idNumber,"batchName=",row.batchName);
              let videoName = row.batchName+"_"+row.idNumber+"_"+type;
              let videoUrl = row.totalBatch+"/"+videoName+".mp4";
              //视频地址先写这,后期改到配置里
              let url = "http://192.168.16.119:9001/images/"+videoUrl;
              console.log("videoUrl=",videoUrl)

              sessionStorage.setItem("videoUrl",'http://192.168.16.119:9001/images/1765267861926932482/20_511681200012212819_2.mp4');
              window.open("viewvideo","_blank");
            },
          //流方法播放视频
          playVideo(row, type) {
            console.log("进入playVideo");
            console.log("row=", row);
            console.log("totalBatch=", row.totalBatch, "idNumber", row.idNumber, "batchName=", row.batchName);
            let videoName = row.batchName + "_" + row.idNumber + "_" + type;
            let videoUrl = row.totalBatch + "/" + videoName + ".mp4";

            this.loadVideo("6666666","1_4865466371306164225_2.mp4");
          },
          loadVideo(videoPath,videoName) {
            const videoPlayer = this.$refs.videoPlayer;
            fetch(`http://127.0.0.1:8080/ftp/getVideo?videoPath=${encodeURIComponent(videoPath)}&videoName=${encodeURIComponent(videoName)}`)
                .then(response => {
                  if (!response.ok) {
                    throw new Error('Network response was not ok');
                  }
                  return response.blob();
                })
                .then(blob => {
                  const videoBlob = new Blob([blob], { type: 'video/mp4' });
                  const videoURL = URL.createObjectURL(videoBlob);
                  videoPlayer.src = videoURL;
                  videoPlayer.play();
                })
                .catch(error => {
                  console.error('There was a problem with your fetch operation:', error);
                });
          }

        },

顺便带后端代码

@CrossOrigin(origins = "*") // 允许任何来源的请求
    @GetMapping("/ftp/getVideo")
    public void getVideo(HttpServletResponse response, @RequestParam String videoPath, @RequestParam String videoName) {
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("UTF-8");

        try {
            ftp.connect(FTPProperties.getServer(), FTPProperties.getPort());
            ftp.login(FTPProperties.getUsername(), FTPProperties.getPassword());
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                throw new RuntimeException("FTP server refused connection.");
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

            InputStream inputStream = ftp.retrieveFileStream(videoPath + "/" + videoName);
            if (inputStream != null) {
                try (OutputStream outputStream = response.getOutputStream()) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    outputStream.flush(); // 确保所有数据已写入输出流
                }
                // 关闭输出流
                response.flushBuffer();
                inputStream.close();
                ftp.logout(); // 登出
            } else {
                throw new RuntimeException("文件未找到");
            }
        } catch (IOException e) {
//            throw new RuntimeException("Error downloading file from FTP server", e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    // log error or handle as needed
                }
            }
        }
    }






    @CrossOrigin(origins = "*") // 允许任何来源的请求
    @GetMapping("/ftp/getVideoList")
    public List<VideoInfo> getVideoList() {
        List<VideoInfo> videoList = new ArrayList<>();

        // 连接FTP服务器
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("UTF-8");

        try {
            int reply;
            ftp.connect(FTPProperties.getServer(), FTPProperties.getPort());
            ftp.login(FTPProperties.getUsername(), FTPProperties.getPassword());
            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
            }

            FTPFile[] files = ftp.listFiles(); // 获取FTP服务器上所有文件
            for (FTPFile file : files) {
                listFilesRecursive(ftp, "/home/ftpuser", videoList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return videoList;
    }


    private void listFilesRecursive(FTPClient ftp, String path, List<VideoInfo> videoList) throws IOException {
        FTPFile[] files = ftp.listFiles(path);
        for (FTPFile file : files) {
            if (file.isDirectory()) {
                // 如果是文件夹,递归进入文件夹
                listFilesRecursive(ftp, path + "/"+ file.getName() , videoList);
            } else if (file.getName().toLowerCase().endsWith(".mp4")) {
                // 处理视频文件
                String videoPath = path ; // 视频文件路径
                String videoName = file.getName(); // 视频文件名称
                videoList.add(new VideoInfo(videoPath, videoName));
            }
        }
    }


  //利用ftp技术,将文件上传到ftp服务器
    @CrossOrigin(origins = "*") // 允许任何来源的请求
    @PostMapping("/uploadFileToFTP")
    //ftp 上传方法
    public  boolean uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("batchId") String batchId) throws IOException {
        boolean flag = uploadFile(FTPProperties.getServer(),FTPProperties.getPort(),FTPProperties.getUsername(),
                FTPProperties.getPassword(),batchId,"video",file.getOriginalFilename(),file.getInputStream());
        //根据反馈输出日志
        if (flag){
            log.info("上传成功,文件名为:"+file.getOriginalFilename()+"文件大小="+file.getSize()+"字节"+"MB="+file.getSize()/1024/1024+"MB");
        }else {
            log.error("上传失败,文件名为:"+file.getOriginalFilename()+"文件大小="+file.getSize()+"字节"+"MB="+file.getSize()/1024/1024+"MB");
        }
            return flag;
    }

    /**
     * #!/bin/bash
     *
     * # 安装vsftpd
     * sudo yum remove vsftpd -y
     * sudo yum install vsftpd -y
     *
     * # 启动vsftpd服务
     * sudo systemctl start vsftpd
     *
     * # 检查服务状态
     * sudo systemctl status vsftpd
     * 云服务器记得开端口
     *
     * 创建一个新用户
     * 切记 必须在/etc/vsftpd/user_list
     *
     * 指定允许使用vsftpd的用户列表文件=》 也就是自己的用户名,要不然访问530错误
     * @param url
     * @param port
     * @param username
     * @param password
     * @param path
     * @param path1
     * @param filename
     * @param input
     * @return
     */

    public  boolean uploadFile(String url,// FTP服务器hostname
                                     int port,// FTP服务器端口
                                     String username, // FTP登录账号
                                     String password, // FTP登录密码
                                     String path, // FTP服务器保存目录
                                     String path1, // FTP服务器保存目录1
                                     String filename, // 上传到FTP服务器上的文件名
                                     InputStream input // 输入流
    ){
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("UTF-8");
        try {
            boolean b = false;
            int reply;
            ftp.connect(url, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();// 获取服务器的响应码。
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(path);  //创建文件夹
            ftp.changeWorkingDirectory(path);  //切换到文件夹
//            ftp.makeDirectory(path1);
//            ftp.changeWorkingDirectory(path1);
             b = ftp.storeFile(filename, input);//最终默认上传到 /home/ftpuser 目录下  批次id目录内
            if (b){
                //异步写入日志
                asynWriteVideoImportLog(path, filename, input);
            }
            input.close();
            ftp.logout();
            success = b;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }
相关推荐
brief of gali3 分钟前
记录一个奇怪的前端布局现象
前端
计算机毕设指导67 分钟前
基于 SpringBoot 的作业管理系统【附源码】
java·vue.js·spring boot·后端·mysql·spring·intellij-idea
Json_181790144801 小时前
电商拍立淘按图搜索API接口系列,文档说明参考
前端·数据库
风尚云网1 小时前
风尚云网前端学习:一个简易前端新手友好的HTML5页面布局与样式设计
前端·css·学习·html·html5·风尚云网
木子02041 小时前
前端VUE项目启动方式
前端·javascript·vue.js
GISer_Jing1 小时前
React核心功能详解(一)
前端·react.js·前端框架
捂月2 小时前
Spring Boot 深度解析:快速构建高效、现代化的 Web 应用程序
前端·spring boot·后端
深度混淆2 小时前
实用功能,觊觎(Edge)浏览器的内置截(长)图功能
前端·edge
Smartdaili China2 小时前
如何在 Microsoft Edge 中设置代理: 快速而简单的方法
前端·爬虫·安全·microsoft·edge·社交·动态住宅代理
秦老师Q2 小时前
「Chromeg谷歌浏览器/Edge浏览器」篡改猴Tempermongkey插件的安装与使用
前端·chrome·edge