当前位置: 首页 > article >正文

文件分块上传

上一篇文章(Java 线程实现暂停、中止)讲了理论,接下来写一个简单的demo,可以实现暂停和恢复上传。
核心就是分块上传,可以把代码里面的数据都放到数据库里即可

import java.io.*;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicLong;

public class FileUploader {

    private static final int BUFFER_SIZE = 1 * 2; // buffer size
    private static final String UPLOAD_STATUS_FILE = "C:\\upload_status.txt"; // Status file to track progress

    private static volatile boolean suspend = false;
    public void uploadFile(String filePath, String serverUrl) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();

        // Create a temporary status file to track the upload progress
        File statusFile = new File(UPLOAD_STATUS_FILE);
        long uploadedBytes = 0;
        if (statusFile.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(statusFile))) {
                uploadedBytes = Long.parseLong(reader.readLine());
            }
        }
        int i =0;
        // Open the file and start uploading from the last uploaded position
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[BUFFER_SIZE];
            AtomicLong currentUploadedBytes = new AtomicLong(uploadedBytes);

            while (currentUploadedBytes.get() < fileSize) {
                while (suspend) {

                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                i++;
                System.out.println("第" +i +"次分块上传");
                int bytesRead = fis.read(buffer);
                if (bytesRead == -1) {
                    break;
                }

                // Upload the chunk to the server
                uploadChunk(serverUrl, buffer, bytesRead, currentUploadedBytes);

                // Update the status file
                updateStatusFile(currentUploadedBytes.get());
            }
        }

        // Remove the status file once the upload is complete
        statusFile.delete();
    }


    private void uploadChunk(String filePath, byte[] buffer, int bytesRead, AtomicLong currentUploadedBytes) throws IOException {
        // Write the chunk to the specified file path
        try (FileOutputStream fos = new FileOutputStream(filePath, true); // Append mode
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            bos.write(buffer, 0, bytesRead);
            currentUploadedBytes.addAndGet(bytesRead);
            System.out.println("Uploading chunk of size " + bytesRead + " bytes");
        }
    }
    private void updateStatusFile(long uploadedBytes) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(UPLOAD_STATUS_FILE))) {
            writer.write(Long.toString(uploadedBytes));
        }
    }
    public static void main(String[] args) {
        String filePath = "C:\\test.png";
        String serverUrl = "C:\\to.png";

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextBoolean()) {
                boolean b = scanner.nextBoolean();
                suspend = b;
                System.out.println("suspend is " + suspend);
            }
        }).start();
        try {
            FileUploader uploader = new FileUploader();
            uploader.uploadFile(filePath, serverUrl);
            System.out.println("Upload completed successfully.");
        } catch (IOException e) {
            System.err.println("Failed to upload file: " + e.getMessage());
        }
    }

}

http://www.kler.cn/news/340624.html

相关文章:

  • 黑神话:仙童,数据库自动反射魔法棒
  • 【自动驾驶汽车通讯协议】I2C(IIC)总线通讯技术详解
  • Windows环境安装CentOS7
  • Lumerical 脚本语言——操作实体对象(Manipulating objects)
  • unix进程间通信信号的有效实践
  • 用KLineChart绘制股票行情K线图
  • 163页PPT罗兰贝格品牌战略升级:华为案例启示与电器集团转型之路
  • 《PyTorch深度学习快速入门教程》学习笔记(第15周)
  • 国产长芯微LUM6100高可靠性双通道双向I2C数字隔离器P2P替代ADUM1250 ADUM1251替代ISO1540 ISO1541
  • zabbix7.0web页面删除主机操作实现过程
  • 接口自动化测试实战
  • k8s的pod的管理
  • MySQL(SQLite3)数据库+Flask框架+HTML搭建个人博客网站
  • 【小沐学GIS】blender导入OpenTopography地形数据(BlenderGIS、OSM、Python)
  • 2024.10.9 QT事件
  • 科创集团所属园区入驻企业北京铭镓半导体获 “硬科技”潜在独角兽企业认定
  • Matlab线条设置
  • 提示工程、微调和 RAG
  • 【ROS2】geometry_msgs::msg::Twist和sensor_msgs::msg::Joy
  • ssm智能社区管理系统的设计与实现