在 Android 中将图像上传到 Cloudinary 失败

Posted

技术标签:

【中文标题】在 Android 中将图像上传到 Cloudinary 失败【英文标题】:Image uploading to Cloudinary Failed in Android 【发布时间】:2019-09-21 08:51:14 【问题描述】:

单击相机中的图像后,我正在尝试将图像上传到 Cloudinary。 相机工作正常,但单击图像后,应用程序一次又一次地崩溃。试图调试它,但没有得到我遇到错误的地方。

LOGCAT:
beginning of crash
05-03 00:29:58.243 4880-4880/com.example.maaz.taxit E/androidRuntime: FATAL EXCEPTION: main
    Process: com.example.maaz.taxit, PID: 4880
    java.lang.RuntimeException: Failure delivering result ResultInfowho=null, request=0, result=-1, data=null to activity com.example.maaz.taxit/com.example.maaz.taxit.ImageDeleteTest: android.os.NetworkOnMainThreadException
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
        at android.app.ActivityThread.-wrap16(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
        at java.net.InetAddress.getAllByName(InetAddress.java:215)
        at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
        at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
        at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
        at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
        at com.cloudinary.android.MultipartUtility.<init>(MultipartUtility.java:52)
        at com.cloudinary.android.UploaderStrategy.callApi(UploaderStrategy.java:48)
        at com.cloudinary.Uploader.callApi(Uploader.java:22)
        at com.cloudinary.Uploader.upload(Uploader.java:55)
        at com.example.maaz.taxit.ImageDeleteTest.onActivityResult(ImageDeleteTest.java:63)
        at android.app.Activity.dispatchActivityResult(Activity.java:6428)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
        at android.app.ActivityThread.-wrap16(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5417) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

我尝试对示例图像 URL 进行硬编码,但仍然无法正常工作。 可能是这条线的问题 cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());

public static final int TAKE_PHOTO_REQUEST = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_REQUEST) 
            if (resultCode == RESULT_OK) 
                //File to upload to cloudinary
                Toast.makeText(this, "Pakistan Zinabad", Toast.LENGTH_SHORT).show();
                Map config = new HashMap();
                config.put("cloud_name", "nomancloud");
                config.put("api_key", "myKey");
                config.put("api_secret", "mySecretApi");
                Cloudinary cloudinary = new Cloudinary(config);

                try 
                    cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());
                 catch (IOException e) 
                    e.printStackTrace();
                

             else if (resultCode == RESULT_CANCELED) 
                // User cancelled the image capture
                //finish();
            
        

    


    private File createImageFile() throws IOException 
        // Create an image file name

        String imageFileName = "capturedImage";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        return image;
    

 @Override
    public void onClick(View v) 

        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) 
        // Create the File where the photo should go
        photoFile = null;

        try 
        photoFile = createImageFile();
        
        catch (IOException ex) 
        // Error occurred while creating the File
        

        // Continue only if the File was successfully created
        if (photoFile != null) 
            takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photoFile));
            startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
            
        
    

【问题讨论】:

【参考方案1】:

您可以尝试使用:

Map uploadResult = cloudinary.uploader().upload("http://res.cloudinary.com/demo/image/upload/sample.jpg", ObjectUtils.emptyMap());

并打印 RuntimeException/uploadResult?

【讨论】:

【参考方案2】:

尝试使用 Cloudinary 提供的适用于 Android 的 MediaManager 类。您将需要调用将在后台线程上运行的 dispatch() 方法。基本上你得到了 NetworkOnMainThread 异常,这意味着你在 Android 不允许的 UI 线程上进行网络调用。查看文档,很简单。

    String requestId = MediaManager.get().upload("imageFile.jpg")
   .unsigned("sample_preset")
   .dispatch();

来自文档的 sn-p。

查看此链接以了解更多信息:

Cloudinary upload documentation page

【讨论】:

以上是关于在 Android 中将图像上传到 Cloudinary 失败的主要内容,如果未能解决你的问题,请参考以下文章

在android中将图像作为BLOB上传到SQL

在未找到android studio照片中将图像上传到网站

在 C# 中将 Base64 字节数组解码为图像

Rails Rollback Transaction 尝试使用carrierwave上传图片时

cloudinary -base 64 图像上传给出无效的 JSON 响应

如何在ios中将图像上传到服务器?