public class UploadUtil {

    // 修改为你的服务端 IP 和端口
    private static final String SERVER_IP = ServerConfig.SERVER_IP;
    private static final int SERVER_PORT = ServerConfig.SERVER_PORT;

    public static void uploadAllFilesInDirectory(File dir) {
        if (dir == null || !dir.exists()) return;

        if (dir.isFile()) {
            try {
                FileSender.sendFileFold(SERVER_IP, SERVER_PORT, dir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File f : files) {
                    uploadAllFilesInDirectory(f); // 递归上传
                }
            }
        }
    }
}


public class FileSender {
    //按照单文件传输到服务器
    public static void send(String host, int port, File file) throws Exception {
        try (Socket socket = new Socket(host, port);
             DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
             FileInputStream fis = new FileInputStream(file)) {

            byte[] nameBytes = file.getName().getBytes("UTF-8");
            dos.writeInt(nameBytes.length);
            dos.write(nameBytes);
            dos.writeLong(file.length());

            byte[] buffer = new byte[4096];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                dos.write(buffer, 0, len);
            }
            dos.flush();
        }
    }


    //根据文件目录上传
    public static void sendFileFold(String serverIp, int port, File file) throws Exception {
        try (Socket socket = new Socket(serverIp, port);
             DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
             FileInputStream fis = new FileInputStream(file)) {

            // 获取根目录(一般是 /storage/emulated/0)
            String root = "/storage/emulated/0";
            String absPath = file.getAbsolutePath();

            // 相对路径(如 Download/abc.jpg)
            String relativePath = absPath.startsWith(root)
                    ? absPath.substring(root.length() + 1)
                    : file.getName();

            // 发送文件名长度和路径名(UTF-8 编码)
            byte[] nameBytes = relativePath.getBytes("UTF-8");
            dos.writeInt(nameBytes.length);
            dos.write(nameBytes);

            // 发送文件大小
            dos.writeLong(file.length());

            // 发送文件内容
            byte[] buffer = new byte[4096];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, len);
            }

            dos.flush();
            System.out.println("文件发送完成: " + relativePath);
        }
    }

}
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐