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;
    }
相关推荐
GIS程序媛—椰子5 分钟前
【Vue 全家桶】7、Vue UI组件库(更新中)
前端·vue.js
DogEgg_00111 分钟前
前端八股文(一)HTML 持续更新中。。。
前端·html
ZL不懂前端14 分钟前
Content Security Policy (CSP)
前端·javascript·面试
木舟100918 分钟前
ffmpeg重复回听音频流,时长叠加问题
前端
王大锤439129 分钟前
golang通用后台管理系统07(后台与若依前端对接)
开发语言·前端·golang
我血条子呢1 小时前
[Vue]防止路由重复跳转
前端·javascript·vue.js
黎金安1 小时前
前端第二次作业
前端·css·css3
啦啦右一1 小时前
前端 | MYTED单篇TED词汇学习功能优化
前端·学习
半开半落1 小时前
nuxt3安装pinia报错500[vite-node] [ERR_LOAD_URL]问题解决
前端·javascript·vue.js·nuxt