2012-03-22 36 views
19

Tôi làm cách nào để tải lên Tệp (tệp đồ họa, âm thanh và video) với Android bằng cách sử dụng API Dropbox cho Dropbox? Tôi đã làm theo hướng dẫn trên trang Dropbox SDK Android và có thể lấy mẫu để hoạt động. Nhưng bây giờ thay vì một chuỗi Tôi muốn tải lên một đối tượng File thực tế và đang đấu tranh.Sử dụng API Dropbox để tải tệp lên bằng Android

Mẫu mã hoạt động mà không bất kỳ vấn đề và trông như thế này:

String fileContents = "Hello World!"; 
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContents.getBytes()); 
try { 
    Entry newEntry = mDBApi.putFile("/testing_123456.txt", inputStream, fileContents.length(), null, null); 
} catch (DropboxUnlinkedException e) { 
    Log.e("DbExampleLog", "User has unlinked."); 
} catch (DropboxException e) { 
    Log.e("DbExampleLog", "Something went wrong while uploading."); 
} 

Nhưng khi tôi cố gắng thay đổi nó và tải lên một tập tin thực tế với mã này:

File tmpFile = new File(fullPath, "IMG_2012-03-12_10-22-09_thumb.jpg"); 

// convert File to byte[] 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
ObjectOutputStream oos = new ObjectOutputStream(bos); 
oos.writeObject(tmpFile); 
bos.close(); 
oos.close(); 
byte[] bytes = bos.toByteArray(); 

ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); 
try { 
    Entry newEntry = mDBApi.putFile("/IMG_2012-03-12_10-22-09_thumb.jpg", inputStream, tmpFile.length(), null, null); 
} catch (DropboxUnlinkedException e) { 
    Log.e("DbExampleLog", "User has unlinked."); 
} catch (DropboxException e) { 
    Log.e("DbExampleLog", "Something went wrong while uploading."); 
} 

Tôi không có thành công gặp lỗi DropboxException. Tôi nghĩ rằng một cái gì đó mà tôi cố gắng để chuyển đổi các đối tượng tập tin vào dòng byte phải sai, nhưng đây chỉ là một giả định.

Khác với ví dụ về Chuỗi không có gì khác được ghi lại trên trang Dropbox dành cho Android.

Cảm ơn bạn đã được trợ giúp.

Trả lời

23

Tôi tìm thấy giải pháp - nếu có ai quan tâm ở đây là mã làm việc:

private DropboxAPI<AndroidAuthSession> mDBApi;//global variable 

File tmpFile = new File(fullPath, "IMG_2012-03-12_10-22-09_thumb.jpg"); 

FileInputStream fis = new FileInputStream(tmpFile); 

      try { 
       DropboxAPI.Entry newEntry = mDBApi.putFileOverwrite("IMG_2012-03-12_10-22-09_thumb.jpg", fis, tmpFile.length(), null); 
      } catch (DropboxUnlinkedException e) { 
       Log.e("DbExampleLog", "User has unlinked."); 
      } catch (DropboxException e) { 
       Log.e("DbExampleLog", "Something went wrong while uploading."); 
      } 
+7

mDBApi là những gì trong mã này? – TharakaNirmana

+1

Tôi biết câu trả lời này là muộn nhưng ai biết nó có thể tiết kiệm một số người. Một biến toàn cầu của nó.Đây là mã mà bạn nên thêm: riêng DropboxAPI mDBApi; – Yenthe

+0

DropboxAPI riêng mDBApi; – nikki

2

@ câu trả lời e-tự nhiên là hơn đúng ... chỉ cần nghĩ rằng tôi muốn chỉ cho mọi người vào trang web chính thức của Dropbox mà hiển thị cách upload a file and much more.

Ngoài ra, câu trả lời @ e-nature sẽ ghi đè các tệp có cùng tên, vì vậy nếu bạn không muốn hành vi đó chỉ đơn giản là sử dụng .putFile thay vì .putFileOverwrite. .putFile có thêm đối số, bạn có thể chỉ cần thêm null vào cuối. More info.

5

Dưới đây là một thực hiện Dropbox API để uploadtải một tập tin. Điều này có thể được triển khai cho bất kỳ loại tệp nào.

String file_name = "/my_file.txt"; 
String file_path = Environment.getExternalStorageDirectory() 
     .getAbsolutePath() + file_name; 
AndroidAuthSession session; 

public void initDropBox() { 

    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET); 
    session = new AndroidAuthSession(appKeys); 
    mDBApi = new DropboxAPI<AndroidAuthSession>(session); 
    mDBApi.getSession().startOAuth2Authentication(MyActivity.this); 

} 

Entry response; 

public void uploadFile() { 
    writeFileContent(file_path); 
    File file = new File(file_path); 
    FileInputStream inputStream = null; 
    try { 
     inputStream = new FileInputStream(file); 
    } catch (FileNotFoundException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 


    try { 
     response = mDBApi.putFile("/my_file.txt", inputStream, 
       file.length(), null, null); 
     Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev); 
    } catch (DropboxException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 

    } 

} 
public void downloadFile() { 

    File file = new File(file_path); 
    FileOutputStream outputStream = null; 

    try { 
     outputStream = new FileOutputStream(file); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    DropboxFileInfo info = null; 
    try { 
     info = mDBApi.getFile("/my_file.txt", null, outputStream, null); 



     Log.i("DbExampleLog", "The file's rev is: " 
       + info.getMetadata().rev); 
    } catch (DropboxException e) { 
     // TODO Auto-generated catch block 

     e.printStackTrace(); 
    } 

} 

@Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     if (mDBApi.getSession().authenticationSuccessful()) { 
      try { 
       // Required to complete auth, sets the access token on the 
       // session 

      mDBApi.getSession().finishAuthentication(); 

      String accessToken = mDBApi.getSession().getOAuth2AccessToken(); 

      /** 
      * You'll need this token again after your app closes, so it's 
      * important to save it for future access (though it's not shown 
      * here). If you don't, the user will have to re-authenticate 
      * every time they use your app. A common way to implement 
      * storing keys is through Android's SharedPreferences API. 
      */ 

     } catch (IllegalStateException e) { 
      Log.i("DbAuthLog", "Error authenticating", e); 
     } 
    } 
} 

-> Gọi UploadFile() và phương pháp trong chủ đề con DownloadFile() nếu không nó sẽ cung cấp cho bạn ngoại lệ

-> Đối với việc sử dụng AsyncTask và gọi đó là các phương pháp nêu trên trong doInBackground phương pháp.

Hy vọng điều này sẽ rất hữu ích ... Cảm ơn

2

Dưới đây là một ví dụ trong đó sử dụng v2 API Dropbox nhưng một SDK bên thứ 3. Nó hoạt động giống hệt nhau đối với Google Drive, OneDrive và Box.com bằng cách này.

// CloudStorage cs = new Box(context, "[clientIdentifier]", "[clientSecret]"); 
// CloudStorage cs = new OneDrive(context, "[clientIdentifier]", "[clientSecret]"); 
// CloudStorage cs = new GoogleDrive(context, "[clientIdentifier]", "[clientSecret]"); 
CloudStorage cs = new Dropbox(context, "[clientIdentifier]", "[clientSecret]"); 
new Thread() { 
    @Override 
    public void run() { 
     cs.createFolder("/TestFolder"); // <--- 
     InputStream stream = null; 
     try { 
      AssetManager assetManager = getAssets(); 
      stream = assetManager.open("UserData.csv"); 
      long size = assetManager.openFd("UserData.csv").getLength(); 
      cs.upload("/TestFolder/Data.csv", stream, size, false); // <--- 
     } catch (Exception e) { 
      // TODO: handle error 
     } finally { 
      // TODO: close stream 
     } 
    } 
}.start(); 

Nó sử dụng CloudRail Android SDK

Các vấn đề liên quan