Aristide13
Aristide13

Reputation: 242

How to upload a file with a link to Google Drive REST API v2

I'm looking for a way to upload a file on google drive from a download link.

I found nothing in the documentation that explains how to do it.

EDIT :

I found two alternatives:

The first solution seems to be the fastest. When I do a file copy / paste from one cloud to another it's much faster with solid explorer for example. There must be a better solution?`

    @Override
    protected String doInBackground(String... sUrl) {
        File body = new File();
        body.setTitle("some name");
        String fileId = null;
        File createdFile;
        InputStream input = null;
        ByteArrayOutputStream bos = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // download the file
            input = connection.getInputStream();
            bos = new ByteArrayOutputStream();

            byte data[] = new byte[4096];
            total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;

                bos.write(data, 0, count);
                //option 2
                if (fileId == null){
                    createdFile = mService.files().insert(body, new ByteArrayContent("", bos.toByteArray())).execute();
                    fileId = createdFile.getId();

                }else{
                    createdFile = mService.files().update(fileId, createdFile, new ByteArrayContent("", bos.toByteArray())).execute();
                }

            }
            //option 1
            createdFile = mService.files().insert(body, new ByteArrayContent("", bos.toByteArray())).execute();
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (bos != null)
                    bos.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }
    ..............

Can you tell me a solution?

Upvotes: 0

Views: 817

Answers (2)

Aristide13
Aristide13

Reputation: 242

Finally I proceeded like this:

@Override
    protected String doInBackground(String... sUrl) {

        com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
        body.setTitle("some name");
        InputStream input = null;
        InputStreamContent mediaContent = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            if (cookies != null){
                connection.setRequestProperty("Cookie", cookies);
                connection.setRequestProperty("User-Agent", agent);
                connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, *" + "/" + "*");
                connection.setRequestProperty("Accept-Language", "en-US,en;q=0.7,he;q=0.3");
                connection.setRequestProperty("Referer", sUrl[0]);
            }
            connection.connect();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            input = connection.getInputStream();

            mediaContent = new InputStreamContent("", new BufferedInputStream(connection.getInputStream()) {
                @Override
                public int read() throws IOException {

                    return 0;
                }
                @Override
                public int read(byte[] buffer,
                                int byteOffset, int byteCount)
                        throws IOException {

                    return super.read(buffer, byteOffset, byteCount);
                }
            });

            com.google.api.services.drive.model.File f = mService.files().insert(body, mediaContent).execute();

        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

I hope this will help.

Upvotes: 0

pinoyyid
pinoyyid

Reputation: 22316

You can't set an arbitrary unique ID. You have two options

  1. Leave it null. The most common mechanism is to not set any ID at all. When you create the file, Google Drive will create an ID and return in createdFile.id.

  2. Request a cache of IDs. You can use https://developers.google.com/drive/v2/reference/files/generateIds to fetch some IDs which are then reserved for you to use. You can set one of these IDs in your body.id.

However, I suspect your real problem is that you have yet to understand the significance of the file ID vs the file name. In Google Drive, files are identified by their ID, not their name. A filename is simply a property of a file, just like modified date and mime-type. If you 10 creates, you will get 10 files. If those creates all had the same name the, guess what, each of the 10 files will have the same name.

If it is your intention to update the same file, rather than create a new one, then you should be using https://developers.google.com/drive/v2/reference/files/update instead of Create.

Upvotes: 1

Related Questions