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;
    }
相关推荐
Jiaberrr7 分钟前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho1 小时前
【TypeScript】知识点梳理(三)
前端·typescript
安冬的码畜日常2 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
小白学习日记2 小时前
【复习】HTML常用标签<table>
前端·html
程序员大金3 小时前
基于SpringBoot+Vue+MySQL的装修公司管理系统
vue.js·spring boot·mysql
丁总学Java3 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
yanlele3 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范
懒羊羊大王呀3 小时前
CSS——属性值计算
前端·css
芯橦3 小时前
【瑞昱RTL8763E】音频
单片机·嵌入式硬件·mcu·物联网·音视频·visual studio code·智能手表