如何将图像拆分为 4MB 的块并在 android 中上传到服务器

How to split the image in the chunks of 4MB and upload to server in android

我想将图像分割成每个 4mb 的块,然后上传到 server.How 我可以实现这个以分块发送图像吗?

我尝试了一些方法,但我收到媒体不支持的错误。

            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL("SERVER_URL");
            connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);//Allow Inputs
            connection.setDoOutput(true);//Allow Outputs
            connection.setUseCaches(false);//Don't use a cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty(
                    "Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file",selectedFilePath);

我想按以下方式输入。

    {
              "blocks": [{
                    "hashdata": "dsfhsdfjhjsdfhj36278dhgjgddfsh7k",
                    "data": <base64 data>
                },{
                    "hashdata": "abcdskjfkskdfh8772384374789327dh",
                    "data": <base64 data>
                }]
     }

最好和最简单的方法是将文件作为字节读取到字节数组中,并将其划分为您想要的任何大小,然后上传到服务器。此方法可用于分割任何类型的文件,无论是图像文件还是文本文件,甚至是二进制文件。

确保你不会对你这样做 UI 主题

      final int MAX_SUB_SIZE = 4194304; // 4*1024*1024 == 4MB
      FileInputStream f = new FileInputStream("pathto/img.png");
      byte[] data = new byte[f.available()];  // Size of original file
      byte[] subData = new byte[MAX_SUB_SIZE];  // 4MB Sized Array

      f.read(data); // Read The Data
      int start = 0;  // From 0
      int end = MAX_SUB_SIZE;    // To MAX_SUB_SIZE bytes
      // Just Saving the size to avoid re-computation
      int max = data.length;
      if(max > 0)
      {

           for( ;end < max; ){
             subData = Arrays.copyOfRange(data, start, end);
             start = end;
             end = end + MAX_SUB_SIZE;
             if(end >= max)
             {
                end = max;
             }

             upload4MB(subData); // This is your method to upload data
           }
           // For the Last Chunk (size less than or equal to 4mb)
           end--; // To avoid a padded zero
           subData = Arrays.copyOfRange(data, start, end);
           upload4MB(subData);
         }

注意

    /*This method used in the abouve code is your
      logic for uploading the file to sever */

      upload4MB(byte[] chunk) 

    /*Either save the chunks to upload it together
     or upload the chunk then and there itself*/

将所有这些放在try-catch 中以捕获可能发生的任何类型的异常。

"subData" 字节数组对应于你的 4mb 数据块做任何你想做的块。

另请参阅此 post 以了解如何使用 Android 和 PHP 作为后端将文件上传到服务器。

Read this Post on Whosebug that shows how to upload files

希望这能解决您的问题。有用的话记得点个赞哦