skip to Main Content

I have a multipart file, it will be an image or video, which needs to be chunked for POST request. How can I chunk the file into byte array segments?

edit: I’m using Twitter API to upload image, according to their docs, media must be chunked

2

Answers


  1. Chosen as BEST ANSWER

    I've found a solution thanks to https://www.baeldung.com/2013/04/04/multipart-upload-on-s3-with-jclouds/

    public final class MediaUtil {
    
        public static int getMaximumNumberOfParts(byte[] byteArray) {
            int numberOfParts = byteArray.length / (1024 * 1024); // 1MB
            if (numberOfParts == 0) {
                return 1;
            }
            return numberOfParts;
        }
    
        public static List<byte[]> breakByteArrayIntoParts(byte[] byteArray, int maxNumberOfParts) {
            List<byte[]> parts = new ArrayList<>();
            int fullSize = byteArray.length;
            long dimensionOfPart = fullSize / maxNumberOfParts;
            for (int i = 0; i < maxNumberOfParts; i++) {
                int previousSplitPoint = (int) (dimensionOfPart * i);
                int splitPoint = (int) (dimensionOfPart * (i + 1));
                if (i == (maxNumberOfParts - 1)) {
                    splitPoint = fullSize;
                }
                byte[] partBytes = Arrays.copyOfRange(byteArray, previousSplitPoint, splitPoint);
                parts.add(partBytes);
            }
    
            return parts;
        }
    }
    
    // Post the request
    int maxParts = MediaUtil.getMaximumNumberOfParts(multipartFile.getBytes());
    
    List<byte[]> bytes = MediaUtil.breakByteArrayIntoParts(multipartFile.getBytes(), maxParts);
    int segment = 0;
    for (byte[] b : bytes) {
        // POST request here
        segment++;
    }
    

  2. Well, you may need this:

    File resource = ResourceUtils.getFile(path);
    if (resource.isFile()) {
        byte[] bytes = readFile2Bytes(new FileInputStream(resource));
    }
    
    
    
    
    
    private byte[] readFile2Bytes(FileInputStream fis) throws IOException {
    
        int length = 0;
        byte[] buffer = new byte[size];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((length = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, length);
        }
        return baos.toByteArray();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search