Resumable upload in Drive Rest API V3

前端 未结 4 1877
你的背包
你的背包 2020-12-05 16:00

I am trying to create a resumable upload session using drive rest API in Android.

As per the documentation the 3 steps needed to be followed are

  1. Start
4条回答
  •  囚心锁ツ
    2020-12-05 16:47

    Maybe this https://github.com/PiyushXCoder/google-drive-ResumableUpload/blob/master/ResumableUpload.java help you out. However, it was written for servlets but you may easily modify it for android instead.

    Well, after getting the comments let me put some extra descriptions.

    However, the "ResumableUpload.java" github repo link is well commented and it is enough to make you clear how to perform this upload on google drive. And, you don't actually need to read this long description.

    As described in https://developers.google.com/drive/v3/web/resumable-upload by google about how to perform a resumable upload

    • We need to make a POST request to inform the server about this upload and get the Session URI to which we'll send our chunks of data for a File. And yeah, we need Access Token for performing this request(Here, the object of Credential has the access token and we'll use it). This request is performed by this method:
    
        public String requestUploadUrl(HttpServletRequest request, HttpServletResponse response, Credential credential, com.google.api.services.drive.model.File jsonStructure) throws MalformedURLException, IOException
            {
                    URL url = new URL("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
                    HttpURLConnection req = (HttpURLConnection) url.openConnection();
                    req.setRequestMethod("POST");
                    req.setDoInput(true);
                    req.setDoOutput(true);
                    req.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
                    req.setRequestProperty("X-Upload-Content-Type", jsonStructure.getMimeType());
                    req.setRequestProperty("X-Upload-Content-Length", String.valueOf(jsonStructure.getSize()));
                    req.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    
                    String body = "{ \"name\": \""+jsonStructure.getName()+"\" }";
                    req.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", body.getBytes().length));
                    OutputStream outputStream = req.getOutputStream();
                    outputStream.write(body.getBytes());
                    outputStream.close();
                    req.connect();
    
                    String sessionUri = null;
    
                    if (req.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        sessionUri = req.getHeaderField("location");
                    }
                    return sessionUri; 
                }
    
    
    • Now, when we've got the Session URI we may proceed to send our data for the requested File, chuck wise. And, let's perform PUT requests for each chunk. Each chuck's size should be in multiples of 256KB . The following method may be used for each chunk.
    
        public int uploadFilePacket(HttpServletRequest request, HttpServletResponse response, String sessionUri, com.google.api.services.drive.model.File jsonStructure, java.io.File file, long chunkStart, long uploadBytes) throws MalformedURLException, IOException
            {
                URL url1 = new URL(sessionUri);
                HttpURLConnection req1 = (HttpURLConnection) url1.openConnection();
    
                req1.setRequestMethod("PUT");
                req1.setDoOutput(true);
                req1.setDoInput(true);
                req1.setConnectTimeout(10000);
    
                req1.setRequestProperty("Content-Type", jsonStructure.getMimeType());
                req1.setRequestProperty("Content-Length", String.valueOf(uploadBytes));
                req1.setRequestProperty("Content-Range", "bytes " + chunkStart + "-" + (chunkStart + uploadBytes -1) + "/" + jsonStructure.getSize());
    
                OutputStream outstream = req1.getOutputStream();
    
                byte[] buffer = new byte[(int) uploadBytes];
                FileInputStream fileInputStream = new FileInputStream(file);
                fileInputStream.getChannel().position(chunkStart);
                if (fileInputStream.read(buffer, 0, (int) uploadBytes) == -1);
                fileInputStream.close();
    
                outstream.write(buffer);
                outstream.close();
    
                req1.connect();
    
                return req1.getResponseCode();
            }
    
    

    The following method uploads a file dividing it into chunks.

    
        public void uploadFile(HttpServletRequest request, HttpServletResponse response, Credential credential, com.google.api.services.drive.model.File jsonStructure, java.io.File file) throws IOException, UploadFileException
            {
                String sessionUrl = requestUploadUrl(request, response, credential, jsonStructure);
    
                for(long i = 1, j = CHUNK_LIMIT;i = jsonStructure.getSize())
                    {
                        j = jsonStructure.getSize() - i + 1;
                    }
                    int responseCode = uploadFilePacket(request, response, sessionUrl, jsonStructure, file, i-1, j);
                    if(!(responseCode == OK || responseCode == CREATED || responseCode == INCOMPLETE)) throw new UploadFileException(responseCode);
                }
            }
    
    

    That's all.

提交回复
热议问题