Java 分片上传

Java 分片上传

public void uploadFile(File file) throws IOException {
    // 每个片段的大小
    int chunkSize = 1024 * 1024;
    // 计算文件总共需要分成多少片段
    int totalChunks = (int) Math.ceil(file.length() / (double) chunkSize);
    // 创建一个临时文件夹用于保存上传的片段
    File tempDir = new File("temp");
    if (!tempDir.exists()) {
        tempDir.mkdir();
    }
    // 读取文件并分成多个片段上传
    try (FileInputStream fis = new FileInputStream(file)) {
        byte[] buffer = new byte[chunkSize];
        for (int i = 0; i < totalChunks; i++) {
            // 读取一个片段的数据
            int bytesRead = fis.read(buffer);
            // 创建一个HTTP连接并上传片段
            HttpURLConnection connection = (HttpURLConnection) new URL("http://example.com/upload").openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setRequestProperty("Content-Length", String.valueOf(bytesRead));
            OutputStream os = connection.getOutputStream();
            os.write(buffer, 0, bytesRead);
            os.flush();
            os.close();
            // 读取服务器返回的响应
            InputStream is = connection.getInputStream();
            byte[] response = new byte[is.available()];
            is.read(response);
            is.close();
            // 将上传成功的片段保存到临时文件中
            File tempFile = new File(tempDir, i + ".part");
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }
    // 将所有片段合并成完整的文件
    File outputFile = new File("output.txt");
    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        for (int i = 0; i < totalChunks; i++) {
            File tempFile = new File(tempDir, i + ".part");
            try (FileInputStream fis = new FileInputStream(tempFile)) {
                byte[] buffer = new byte[chunkSize];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
            }
            tempFile.delete();
        }
    }
    tempDir.delete();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值