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;
    }
相关推荐
FungLeo11 小时前
成为全栈·React 管理后台篇·总复盘:从“接口能调通”到“后台值得使用”
前端·react.js·前端框架·项目复盘·成为全栈
allnlei11 小时前
Opus In-Band FEC 详解:原理、实现与开源方案
ffmpeg·音视频·gstreamer
爱吃提升12 小时前
文生视频模型发展趋势(2026)
人工智能·音视频
Csvn12 小时前
并发模式:让渲染学会排队、插队和让路
前端
可乐鸡翅yeah_13 小时前
新手梳理:M3U8 线上问题,哪些是前端锅,哪些是后端锅
前端·ios·音视频·实时音视频·m3u8·音视频在线播放
Flynt13 小时前
Linear 用 1000 个 PR 换掉 styled-components,我写了 200 个按钮,把这笔账复现了一遍
前端·css·preact
JavaGuide14 小时前
NVIDIA 又开源了!这次给 AI Agent 加上权限管控
前端·后端
excel14 小时前
prisma 如何处理数据库竞态
前端·数据库·后端
apple_6926588514 小时前
最新ComfyUI 0.37.1使用教程:画图、3D、音频都有改动 ComfyUI升级到0.37.1啦,新增或改进五大功能
音视频
莪_幻尘15 小时前
Skill 体检:30 个 Skill 全凭感觉?体检器先自曝了 8 个“假 0 分
前端·人工智能·llm