当前位置: 首页 > 知识库问答 >
问题:

如何上传图片到Dropbox?

相俊迈
2023-03-14

我正在尝试从Gallery上传所选图像到dropbox。我被贴了好几天,因为我无法恢复运行时异常

我的onActivityResult()是

 if(requestCode == PIC_UPLOAD) {

    System.out.println("Reahced 1");

    Uri selectedImage = data.getData();
    String[] filePathColumn ={MediaStore.Images.Media.DATA};

    Cursor cursor = getContentResolver().query(selectedImage,
                     filePathColumn, null, null, null); cursor.moveToFirst();

    System.out.println("Reahced 2");

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
   String filePath = cursor.getString(columnIndex); 
   cursor.close();


    Uri imageUri=data.getData();
   List<NameValuePair> params = new ArrayList<NameValuePair>(1); 
   params.add(new  BasicNameValuePair("image", imageUri.getPath()));
    System.out.println("Reahced 3");


    /* String outPath = imageUri.toString(); File outFile = new
       File(outPath); FileInputStream fis = new FileInputStream(outFile);
       mDBApi.putFileOverwriteRequest("/Pic1", fis, outFile.length(),null);
    */

   Uri photoUri = data.getData(); 
   String[] proj = {MediaStore.Images.Media.DATA };
   Cursor actualimagecursor = managedQuery(photoUri, proj,null, null, null);
   int actual_image_column_index =
   actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   actualimagecursor.moveToFirst();
   String img_path =actualimagecursor.getString(actual_image_column_index);

   System.out.println("Image location: " + img_path);

   System.out.println("Reached 1"); 

   uploadDropbox(img_path);
}

uploadDropbox正文为:

    private void uploadDropbox(String URL) {
    // TODO Auto-generated method stub
        AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
        AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
        mDBApi = new DropboxAPI<AndroidAuthSession>(session);

        System.out.println(URL);

        System.out.println("Reahced 4");

        mDBApi.getSession().startAuthentication(MyCamActivity.this);

        System.out.println("Reahced 5");

//      AccessTokenPair access = getStoredKeys();
//      mDBApi.getSession().setAccessTokenPair(access);

        FileInputStream inputStream = null;
        try {
            File file = new File(URL.toString());
            inputStream = new FileInputStream(file);
            com.dropbox.client2.DropboxAPI.Entry newEntry = mDBApi.putFile("/testing.txt", inputStream, file.length(), null, null);
            Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
        } catch (DropboxUnlinkedException e) {
            // User has unlinked, ask them to link again here.
            Log.e("DbExampleLog", "User has unlinked.");
        } catch (DropboxException e) {
            Log.e("DbExampleLog", "Something went wrong while uploading.");
        } catch (FileNotFoundException e) {
            Log.e("DbExampleLog", "File not found.");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {}
            }
        }
    }
protected void onResume() {
    super.onResume();

    if (mDBApi.getSession().authenticationSuccessful()) {
      try {
        // MANDATORY call to complete auth.
        // Sets the access token on the session
        mDBApi.getSession().finishAuthentication();

        AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair();

        // Provide your own storeKeys to persist the access token pair
        // A typical way to store tokens is using SharedPreferences
        storeKeys(tokens.key, tokens.secret);
        } catch (IllegalStateException e) {
          Log.i("DbAuthLog", "Error authenticating", e);
        }
    }

}

private AccessTokenPair getStoredKeys(){//TODO自动生成的方法存根

return  mDBApi.getSession().getAccessTokenPair();

}

private void storeKeys(String key,String secret){//TODO自动生成的方法存根

    // Save the access key for later
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    Editor edit = prefs.edit();
    edit.putString(ACCESS_KEY_NAME, key);
    edit.putString(ACCESS_SECRET_NAME, secret);
    edit.commit();
}

AndroidManifest.xml

    <activity
  android:name="com.dropbox.client2.android.AuthActivity"
  android:launchMode="singleTask"
  android:configChanges="orientation|keyboard">
  <intent-filter>
    <!-- Change this to be db- followed by your app key -->
    <data android:scheme="db-MyKey" />
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.BROWSABLE"/>
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>


    <activity
        android:name=".MyCamActivity"
        android:label="@string/app_name" 
        android:screenOrientation="nosensor" android:configChanges="keyboardHidden|orientation"
        android:uiOptions="splitActionBarWhenNarrow"
        android:clearTaskOnLaunch="true"
        >

错误**:

01-23 14:58:00.855: D/dalvikvm(4238): GC_FOR_ALLOC freed 104K, 2% free 12729K/12935K, paused 16ms
01-23 14:58:00.894: I/System.out(4238): Its not null
01-23 14:58:00.901: D/AndroidRuntime(4238): Shutting down VM
01-23 14:58:00.901: W/dalvikvm(4238): threadid=1: thread exiting with uncaught exception (group=0x40a511f8)
01-23 14:58:00.901: E/AndroidRuntime(4238): FATAL EXCEPTION: main
01-23 14:58:00.901: E/AndroidRuntime(4238): java.lang.RuntimeException: Unable to resume activity {cam.pack/cam.pack.MyCamActivity}: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2444)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1986)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.os.Looper.loop(Looper.java:137)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.ActivityThread.main(ActivityThread.java:4424)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at java.lang.reflect.Method.invoke(Method.java:511)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at dalvik.system.NativeStart.main(Native Method)
01-23 14:58:00.901: E/AndroidRuntime(4238): Caused by: java.lang.NullPointerException
01-23 14:58:00.901: E/AndroidRuntime(4238):     at cam.pack.MyCamActivity.onResume(MyCamActivity.java:571)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1154)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.Activity.performResume(Activity.java:4539)
01-23 14:58:00.901: E/AndroidRuntime(4238):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2434)
01-23 14:58:00.901: E/AndroidRuntime(4238):     ... 12 more

共有1个答案

丁茂
2023-03-14

我犯了一个错误,我把dropbox会话放在我自己定义的函数UploadDropbox()中,这是一个错误导致NullPointerException,因为如果我打印MDBAPI,那么它的NULL。它没有初始化。我们必须将这些行放入oncreate()中,现在它开始工作了,图像正在Dropbox的CameraUploads文件夹中上传

谢谢你的评论。

 类似资料:
  • 本文向大家介绍SpringBoot如何上传图片,包括了SpringBoot如何上传图片的使用技巧和注意事项,需要的朋友参考一下 1.前端准备 2.实现文件上传的步骤说明 3.代码解释 3.1 前提 MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。 3.2 封装文件的上传路径 封装文件上传的路径,如果文件存在直接封装,如果文件不

  • 为了排除可能的其他问题,我可以使用update.json方法成功地将状态更新发布到Twitter。 我还尝试使用client.addfile方法和Fiddler,看起来一切都就绪了。但我不断得到的错误信息是

  • 我想上传一张图片,我正在使用http。客户端()用于发出请求, 请求的主体和编码部分应该是什么?

  • 问题内容: 在过去的几天里,我一直在努力用jQuery和AJAX提交表单。我面临的问题是在表单字段中上传图像。 我的表格是这样的: 我的用于获取表单值的jQuery脚本如下所示: 但是,如果image返回null,则返回除image 1以外的所有字段值。 如何存储在数据数组中? 我要存储,以便可以通过AJAX将值发送到服务器。 问题答案: 对于上传单个图像,像这样 对于多张图片,您将不得不循环不同

  • 上传证件照片。支持 jpeg、jpg、bmp、png 格式,图片大小不超过2M。 // $path string 图片路径 $response = $app->media->upload($path);

  • 问题内容: Q.1我想将这种形式转换为ajax,但似乎我的ajax代码缺少某些内容。提交根本不做任何事情。 Q2。我还希望在选择文件时不等待提交时在更改时触发该函数。 这是JS。 和HTMl与php。 问题答案: 首先在ajax调用中包含成功和错误功能,然后检查它是否给您错误或什么? 您的代码应该像这样