美文网首页
FTP连接获取视频文件转为二进制保存

FTP连接获取视频文件转为二进制保存

作者: 不二不二熊 | 来源:发表于2019-12-11 09:42 被阅读0次
一、需求

需要将接收到的FTP视频路径转为视频流二进制存储进数据库。

二、编码

ftp 获取文件流方法

                          FTPClient ftpClient = new FTPClient();
                            try {
                                ftpClient.connect("ftp的ip地址", Integer.parseInt("21"));
                                ftpClient.login("用户名", "密码");
                                //是否成功登录服务器
                                int replyCode = ftpClient.getReplyCode();
                                System.out.println(replyCode);
                                if (!FTPReply.isPositiveCompletion(replyCode)) {
                                    ftpClient.disconnect();
                                    LOGGER.error("--ftp连接失败--");
                                }
                                //这句最好加告诉对面服务器开一个端口
                                ftpClient.enterLocalPassiveMode();
                            } catch (SocketException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            InputStream inputStream = ftpClient.retrieveFileStream(path);
                            byte[] spbyte = new byte[0];
                            try {
                                if(inputStream!=null){
                                    spbyte = CommonUtil.toByteArray(inputStream);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            inputStream.close();
                            ftpClient.completePendingCommand();
                            if (ftpClient != null && ftpClient.isConnected()) {
                                ftpClient.logout();
                                ftpClient.disconnect();
                            }

CommonUtil转换工具类

 /**
     * <一句话功能描述>: INPUTsTREAM转字节数组
     * <功能详细描述>:
     * @param input
     * @return byte[]
     */
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
三、插入

数据库为 blob字段,java实体类为byte[]类型。普通的mybatis 插入即可。

相关文章

网友评论

      本文标题:FTP连接获取视频文件转为二进制保存

      本文链接:https://www.haomeiwen.com/subject/trxogctx.html