KKFileView(五)

2021SC@SDUSC

文件上传

文件在预览之前需要上传至本地文件夹,因此有工具类downloadutils

1.获取文件真实路径

private static String getRelFilePath(String fileName, FileAttribute fileAttribute) {
        String type = fileAttribute.getSuffix();
        if (null == fileName) {
            UUID uuid = UUID.randomUUID();
            fileName = uuid + "." + type;
        } else { // 文件后缀不一致时,以type为准(针对simText【将类txt文件转为txt】)
            fileName = fileName.replace(fileName.substring(fileName.lastIndexOf(".") + 1), type);
        }
        String realPath = fileDir + fileName;
        File dirFile = new File(fileDir);
        if (!dirFile.exists() && !dirFile.mkdirs()) {
            logger.error("创建目录【{}】失败,可能是权限不够,请检查", fileDir);
        }
        return realPath;
    }

 2. 判断文件来源,ftp/http

若来源于http,调用FileUtils中的copyUrlToFile方法 => 此方法URL对应的文件复制一份

 if (isHttpUrl(url)) {
                File realFile = new File(realPath);
                FileUtils.copyURLToFile(url,realFile);
            }

若来源于ftp,构造ftputils类,调用其中的download方法,主要通过ftpclient进行文件的读写

 URL url = new URL(ftpUrl);
        String host = url.getHost();
        int port = (url.getPort() == -1) ? url.getDefaultPort() : url.getPort();
        String remoteFilePath = url.getPath();
        LOGGER.debug("FTP connection url:{}, username:{}, password:{}, controlEncoding:{}, localFilePath:{}", ftpUrl, username, password, controlEncoding, localFilePath);
        FTPClient ftpClient = connect(host, port, username, password, controlEncoding);
        OutputStream outputStream = new FileOutputStream(localFilePath);
        ftpClient.enterLocalPassiveMode();
        boolean downloadResult = ftpClient.retrieveFile(new String(remoteFilePath.getBytes(controlEncoding), StandardCharsets.ISO_8859_1), outputStream);

猜你喜欢

转载自blog.csdn.net/eldrida1/article/details/121214723