GoogleDrive上传大型文件-java

史鸿运
2023-12-01

继上一篇Googledrive开发后的第二篇,APP整合GoogleDirve功能,这篇主要写一下上传大型文件这个坑,新手上路最苦的是找不到事例,硬着头皮过河强行摸出了这个GoogleDrive 的 upload large file 的用法

Android整合Google的文章太少了,写一篇记录一下自己所踩的坑
先放官方问文档:
GoogleDrive
其次就是得有个google账号,这部分略过

其他GoogledriveAPI:第一篇Googledrive相关API

主要方法:分块上传byte字节

接下来进入正题:

/*主要的参数如下*/
long chunkFileSize = 20* 1024 * 256;


  /**
     * 申请sessionURL
     */
    public void uploadBigFiles(File srcFile, String title, final String folderId, final StateCallback callback, boolean isMoreThan10M) {
        String requestBody = "{\"name\": \"" + title + "\"}";
        if (isMoreThan10M) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL requestUrl = new URL("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
                            HttpURLConnection request = (HttpURLConnection) requestUrl.openConnection();
                            request.setRequestMethod("POST");
                            request.setDoInput(true);
                            request.setDoOutput(true);
                            request.setRequestProperty("Authorization", getAuthToken());
                            request.setRequestProperty("X-Upload-Content-Type", "application/octet-stream.");
//                    request.setRequestProperty("X-Upload-Content-Length","10240");
                            request.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//                            request.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", requestBody.getBytes().length));
                            OutputStream outputStream = request.getOutputStream();
                            outputStream.write(requestBody.getBytes());
                            outputStream.close();
      request.connect();
                            if (request.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                uploadStringChunk(srcFile,new URL(request.getHeaderField("location")));
                            }
        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
   } else {
            uploadFile(srcFile, title, folderId, callback);
        }
    }

接下来是分块上传:

  /**
     * 发送请求包数据_分块上传
     */
    public void uploadStringChunk(File file,URL url ) {
    
        long number = (long) Math.ceil(file.length() * 1.0 / chunkFileSize);
        try {
            RandomAccessFile raf_read = new RandomAccessFile(file, "r");
            for (int i = 0; i < number; i++) {
                HttpURLConnection request = (HttpURLConnection) url.openConnection();
                request.setRequestMethod("PUT");
                request.setDoOutput(true);
                request.setDoInput(true);
                request.setConnectTimeout(10000);
                request.setChunkedStreamingMode(0);

                long startIndex = i * chunkFileSize;
                long contentLength = i == number - 1 ? file.length() - startIndex : chunkFileSize;
                raf_read.seek(startIndex);
                request.setRequestProperty("Content-Length", String.valueOf(contentLength));
                request.setRequestProperty("Content-Range", String.format(" bytes %d-%d/%d", startIndex, startIndex + contentLength-1, file.length()));
                OutputStream outputStream = request.getOutputStream();
                byte[] b = new byte[1024 * 4];
                int len;
                long writeBytes = 0;
                while ((len = raf_read.read(b)) != -1) {
                    boolean overByte = false;
                    if (writeBytes >= contentLength) {
                        overByte = true;
                        len = (int) (contentLength - writeBytes);
                    }

                    outputStream.write(b, 0, len);
                    writeBytes += len;
                    if (overByte) break;
                }
                request.connect();
                if (request.getResponseCode() == HttpURLConnection.HTTP_OK || request.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                } else {

                }
            }

            raf_read.close();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
         
        }

    }

转载请注明出处

 类似资料: