Resumable uploads (Google Drive SDK for Android or Java)

后端 未结 1 734
慢半拍i
慢半拍i 2021-02-06 13:03

I had referred to Check progress for Upload & Download, Resumable upload using Drive API for Android and Direct and Resumable Media Uploads.

However, I cannot get s

相关标签:
1条回答
  • 2021-02-06 13:31

    It seems that MediaHttpUploader did not handle resume upload well. The reason is that "Request the upload status." mentioned in Google Drive SDK Upload Files always fail to get Content-Range.

    So, The way to solve it is polling Content-Range all the time during upload. Thus it's able to resuming an interrupted upload by "Resume the upload from the point where it left off."

    private String getUploadID(Uri fileUri, String token) {         
        Log.d(LOG_TAG, "[sendResumableHttpRequest] +++");
    
        String upload_id = "";
    
        java.io.File fileContent = new java.io.File(fileUri.getPath());
        String fileName = fileContent.getName();
        String contentLength = String.valueOf(fileContent.length());
        String mimeType = getMimeFromURI(fileUri);
    
        Log.d(LOG_TAG, "[sendResumableHttpRequest] fileName : " + fileName);
        Log.d(LOG_TAG, "[sendResumableHttpRequest] contentLength : " + contentLength);
        Log.d(LOG_TAG, "[sendResumableHttpRequest] mimeType : " + mimeType);
    
        try {
            String url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable";
            URL obj = new URL(url);
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    
            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "Bearer " + token);
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            con.setRequestProperty("X-Upload-Content-Type", mimeType);
            con.setRequestProperty("X-Upload-Content-Length", contentLength);       
    
            JSONObject jobj = new JSONObject();
            jobj.put("title", fileName);
            byte[] postData = jobj.toString().getBytes();           
    
            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.write(postData);
            wr.flush();
            wr.close();
    
            int responseCode = con.getResponseCode();
            String location = con.getHeaderField("Location");
            if (location.contains("upload_id")) {
                String[] uploadParameters = location.split("upload_id");
                upload_id = uploadParameters[1].replace("=", "");
            }
    
            Log.d(LOG_TAG, "[sendResumableHttpRequest] Response Code : " + responseCode);
            Log.d(LOG_TAG, "[sendResumableHttpRequest] Response Location : " + location);
            Log.d(LOG_TAG, "[sendResumableHttpRequest] Response uploadID : " + upload_id);
    
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
    
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();            
        }               
    
        Log.d(LOG_TAG, "[sendResumableHttpRequest] ---");
    
        return upload_id;
    }
    
    private void putFileWithUploadID(Uri fileUri, String token, long range) {       
        Log.d(LOG_TAG, "[putFileWithUploadID] +++");
    
        java.io.File fileContent = new java.io.File(fileUri.getPath());
        String fileName = fileContent.getName();
        String contentLength = String.valueOf(fileContent.length());
        String mimeType = getMimeFromURI(fileUri);
    
        Log.d(LOG_TAG, "[putFileWithUploadID] fileName : " + fileName);
        Log.d(LOG_TAG, "[putFileWithUploadID] contentLength : " + contentLength);
        Log.d(LOG_TAG, "[putFileWithUploadID] mimeType : " + mimeType);
    
        long totalBytesFromDataInputStream = 0;
    
        try {
            String url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=" + mUploadID;
            URL obj = new URL(url);
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    
            //add reuqest header
            con.setRequestMethod("PUT");
            con.setRequestProperty("Authorization", "Bearer " + token);
            con.setRequestProperty("Content-Type", mimeType);
            //con.setFixedLengthStreamingMode(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
    
            long nextByte = 0;
            if (range == 0) {               
                con.setRequestProperty("Content-Length", contentLength);
            }
            else {
                nextByte = range + 1;
                long remainContentLength = Long.parseLong(contentLength) - nextByte;
                con.setRequestProperty("Content-Length", String.valueOf(remainContentLength));
                String contentRange = "bytes " + (range + 1) + "-" + ( Long.parseLong(contentLength) - 1) + "/" + contentLength;
                con.setRequestProperty("Content-Range", contentRange);
    
                Log.d(LOG_TAG, "[putFileWithUploadID] Content-Length : " + String.valueOf(remainContentLength));
                Log.d(LOG_TAG, "[putFileWithUploadID] Content-Range : " + contentRange);
            }
            con.setDoOutput(true);          
    
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    
            @SuppressWarnings("resource")
            DataInputStream inputStream = new DataInputStream(new FileInputStream(fileContent)); 
    
            int bytes = 0;              
            byte[] bufferOut = new byte[1024];
            while ((bytes = inputStream.read(bufferOut)) != -1) {               
                if (nextByte > 0) {
                    nextByte = nextByte - bytes;
                    if (nextByte >= 0) continue;
                }
                wr.write(bufferOut, 0, bytes);  
                totalBytesFromDataInputStream += bytes;
            }                                  
            Log.d(LOG_TAG, "[putFileWithUploadID] totalBytesFromDataInputStream:" + totalBytesFromDataInputStream);
            wr.flush();
            wr.close();
    
            int responseCode = con.getResponseCode();
    
            Log.d(LOG_TAG, "[putFileWithUploadID] Response Code : " + responseCode);
    
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
    
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
    
            isUploadCompleted = true;
            isInterrupted = false;
            mLastUploadBytes = 0;
            Log.d(LOG_TAG, "[putFileWithUploadID] isUploadCompleted:" + isUploadCompleted);
            Log.d(LOG_TAG, "[putFileWithUploadID] isInterrupted:" + isInterrupted);
        } catch (Exception e) {
            e.printStackTrace();            
            isInterrupted = true;
            Log.d(LOG_TAG, "[putFileWithUploadID] isInterrupted:" + isInterrupted);
            Log.d(LOG_TAG, "[putFileWithUploadID] totalBytesFromDataInputStream:" + totalBytesFromDataInputStream);
        } finally {
        }
    
        Log.d(LOG_TAG, "[putFileWithUploadID] ---");
    }
    
    private void putFileWithUploadID(Uri fileUri, String token) {   
        putFileWithUploadID(fileUri, token, 0);
    }   
    
    private long requestUploadStatus(Uri fileUri, String token) {           
        Log.d(LOG_TAG, "[requestUploadStatus] +++");
    
        String range_so_far = "0";
    
        java.io.File fileContent = new java.io.File(fileUri.getPath());
        String contentLength = String.valueOf(fileContent.length());
    
        Log.d(LOG_TAG, "[requestUploadStatus] contentLength : " + contentLength);
    
        try {
            String url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=" + mUploadID;
            URL obj = new URL(url);
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    
            //add reuqest header
            con.setRequestMethod("PUT");
            con.setRequestProperty("Authorization", "Bearer " + token);
            con.setRequestProperty("Content-Length", "0");
            con.setRequestProperty("Content-Range", "bytes */*");           
    
            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.flush();
            wr.close();
    
            int responseCode = con.getResponseCode();
            String rangeHeader = con.getHeaderField("Range");
            if (rangeHeader != null && rangeHeader.length() > 0) {
                String[] range = rangeHeader.split("-");
                range_so_far = range[1];
            }
    
            Log.d(LOG_TAG, "[requestUploadStatus] Response Code : " + responseCode);
            Log.d(LOG_TAG, "[requestUploadStatus] Response rangeHeader : " + rangeHeader);
            Log.d(LOG_TAG, "[requestUploadStatus] Response range_so_far : " + range_so_far);                        
    
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
    
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
    
            in.close();
        } catch (Exception e) {
            e.printStackTrace();            
        }               
    
        Log.d(LOG_TAG, "[requestUploadStatus] ---");
    
        return Long.parseLong(range_so_far);
    }   
    
    0 讨论(0)
提交回复
热议问题