woong's

Google Drive 사용하기(2) 업로드 본문

Develop/Android

Google Drive 사용하기(2) 업로드

dlsdnd345 2016. 2. 13. 23:25
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Google Drive 사용하기(2) 업로드


이제 준비가 다 끝났습니다 .


업로드하는 코드를 이용해서 파일 업로드를 진행해 보겠습니다 .


우선 매니페스트 쪽에 퍼미션을 등록합니다 .


1
2
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.INTERNET" />



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package com.example.drivequickstart;
 
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
 
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
 
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
 
public class MainActivity extends Activity {
  static final int REQUEST_ACCOUNT_PICKER = 1;
  static final int REQUEST_AUTHORIZATION = 2;
  static final int CAPTURE_IMAGE = 3;
 
  private static Uri fileUri;
  private static Drive service;
  private GoogleAccountCredential credential;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
    startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
  }
 
  @Override
  protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
    case REQUEST_ACCOUNT_PICKER:
      if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
        String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        if (accountName != null) {
          credential.setSelectedAccountName(accountName);
          service = getDriveService(credential);
          startCameraIntent();
        }
      }
      break;
    case REQUEST_AUTHORIZATION:
      if (resultCode == Activity.RESULT_OK) {
        saveFileToDrive();
      } else {
        startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
      }
      break;
    case CAPTURE_IMAGE:
      if (resultCode == Activity.RESULT_OK) {
        saveFileToDrive();
      }
    }
  }
 
  private void startCameraIntent() {
    String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES).getPath();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
    fileUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_"
        + timeStamp + ".jpg"));
 
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    startActivityForResult(cameraIntent, CAPTURE_IMAGE);
  }
 
  private void saveFileToDrive() {
    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          // File's binary content
          java.io.File fileContent = new java.io.File(fileUri.getPath());
          FileContent mediaContent = new FileContent("image/jpeg", fileContent);
 
          // File's metadata.
          File body = new File();
          body.setTitle(fileContent.getName());
          body.setMimeType("image/jpeg");
 
          File file = service.files().insert(body, mediaContent).execute();
          if (file != null) {
            showToast("Photo uploaded: " + file.getTitle());
            startCameraIntent();
          }
        } catch (UserRecoverableAuthIOException e) {
          startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });
    t.start();
  }
 
  private Drive getDriveService(GoogleAccountCredential credential) {
    return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
        .build();
  }
 
  public void showToast(final String toast) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
      }
    });
  }
}


구글 예제 소스 입니다 .

업로드 예제 소스입니다 .


구글 아이디로 인증을 하고 인증 완료후 사진을 찍으면 구글드라이브로 이미지가 업로드 되는 

코드입니다 .


저는 이소스를 바탕으로 수정을 해서 파일을 업로드 하였습니다 .

 

saveFileToDrive 메서드를 조금만 손보면 충분히 db 파일이나 다른 파일들도 업로드가 가능합니다 .


제가 수정한 파일 업로드 입니다 .


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
try {
                List<File> result = new ArrayList<File>();
                Files.List request = service.files().list();
 
                FileList files = request.execute();
                result.addAll(files.getItems());
                request.setPageToken(files.getNextPageToken());
 
                if (result.size() == 0) {
                    String path = "data/data/com.iw.booklibrary/databases/Book.db";
                    java.io.File fileContent = new java.io.File(path);
                    FileContent mediaContent = new FileContent("image/png", fileContent);
                    File body = new File();
                    body.setTitle(fileContent.getName());
 
                    service.files().insert(body, mediaContent).execute();
                    isOk = true;
                } else {
                    for (int i = 0; i < result.size(); i++) {
                        if ("Book.db".equals(result.get(i).getTitle().toString())) {
                            String path = "data/data/com.iw.booklibrary/databases/Book.db";
                            googleUpLoadDownLoad.updateFile(service, result.get(i).getId(),
                                    "Book.db""수정""image/png", path, true);
                            isOk = true;
                        }
                    }
                }
 
            } catch (UserRecoverableAuthIOException e) {
                startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                dialog.dismiss();
                cancel(true);
            } catch (IOException e) {
                e.printStackTrace();
            }



구글 드라이브를 통해 test 하던중 업로드는 파일이 계속해서 추가가 되는것을 확인했습니다 .

이렇게 되면 다운로드시에 어떤파일인지 제대로 받아오질 못하는 오류가 있었습니다 .


처음에는 삭제를 해주고 파일을 업로드 하려 했으나 삭제를 해도 휴지통에 파일이 있으면

휴지통에 있는 파일을 참조해 오도록 되있는것 같습니다 .


그래서 업로드 하기전에 해당 이름으로 된 파일이 없는지 확인을하고 없으면 업로드를 하고 

있으면 수정을 통해 오류를 해결했습니다.

 

아래 해당 코드는 구글에서 제공해주는 updateFile 과 downLoadFile 을 클래스화 시켜놓은 코드입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class GoogleUpLoadDownLoad {
 
    public File updateFile(Drive service, String fileId, String newTitle,
            String newDescription, String newMimeType, String newFilename, boolean newRevision) {
        try {
            // First retrieve the file from the API.
            File file = service.files().get(fileId).execute();
 
            // File's new metadata.
            file.setTitle(newTitle);
            file.setDescription(newDescription);
            file.setMimeType(newMimeType);
 
            // File's new content.
            java.io.File fileContent = new java.io.File(newFilename);
            FileContent mediaContent = new FileContent(newMimeType, fileContent);
 
            // Send the request to the API.
            File updatedFile = service.files().update(fileId, file, mediaContent).execute();
 
            return updatedFile;
        } catch (IOException e) {
            System.out.println("An error occurred: " + e);
            return null;
        }
    }
 
    public InputStream downloadFile(Drive service, File file) {
 
        if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
            try {
 
                HttpResponse resp =
                        service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
                                .execute();
                return resp.getContent();
            } catch (IOException e) {
                // An error occurred.
                e.printStackTrace();
                return null;
            }
        } else {
            // The file doesn't have any content stored on Drive.
            return null;
        }
    }
 
    public Drive getDriveService(GoogleAccountCredential credential) {
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
                .build();
    }
 
}


'Develop > Android' 카테고리의 다른 글

Android Google Chart 사용하기  (0) 2016.02.13
Google Drive 사용하기(3) 다운로드  (0) 2016.02.13
Google Drive 사용하기(1)  (0) 2016.02.13
Google Drive 준비 하기  (0) 2016.02.13
Android ORM 소개 & ORMLite 사용하기  (1) 2016.02.13
Comments