Java 8:如何为 POST 请求分块多部分文件

Java 8: How to chunk multipart file for POST request

我有一个多部分文件,它将是一个图像或视频,需要根据 POST 请求进行分块。如何将文件分块为字节数组段?

编辑:我正在使用 Twitter API 上传图片,根据他们的文档,媒体必须分块

嗯,你可能需要这个:

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();
}

感谢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++;
}