从Android上传图像到GCS

24
我正试图直接从Android上传图像到Google云存储。但是API似乎不起作用。它们有一些与应用引擎绑定的Java示例,但我没有看到任何已经被证明可在Android上使用的示例。
在Android上,我尝试使用JSON API上传图片。我能够上传图片对象,但似乎它是损坏的。此外,生成身份验证令牌也似乎很棘手。
我现在被困住了。有人在地球上尝试过使用Java客户端或Json API从Android上传图像/视频并成功了吗?请有人指点我正确的方向。使用谷歌的Storage API的这种体验非常令人失望。如果有人做过,请分享您的经验。
以下是我在Android上尝试使用GCS的JSON API时所尝试的代码。
private static String uploadFile(RichMedia media) {
    DefaultHttpClient client = new DefaultHttpClient();
    Bitmap bitmap = BitmapUtils.getBitmap(media.getLocalUrl());
    HttpPost post = new HttpPost(GCS_ROOT + media.getLocalUrl() + "_" + System.currentTimeMillis());
    if(media.getType() == RichMedia.RichMediaType.PICTURE) {
        post.setHeader("Content-Type", "image/jpeg");
    } else {
        post.setHeader("Content-Type", "video/mp4");
    }
    post.setHeader("Authorization", "AIzaSyCzdmCMwiMzl6LD7R2obF0xSgnnx5rEfeI");
    //post.setHeader("Content-Length", String.valueOf(bitmap.getByteCount()));
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] byteArray = stream.toByteArray();

    try {
        post.setEntity(new StringEntity(new Gson().toJson(byteArray).toString()));
        HttpResponse response = client.execute(post);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String eachLine = null;
        StringBuilder builder = new StringBuilder();
        while ((eachLine = reader.readLine()) != null) {
            builder.append(eachLine);
        }
        L.d("response = " + builder.toString());
        JSONObject object = new JSONObject(builder.toString());
        String name = object.getString("name");
        return  name;
    } catch (IOException e) {
        L.print(e);
    } catch (JSONException e) {
        L.print(e);
    }
    return null;
}

我在这里遇到了两个问题。

  1. 上传到服务器的文件损坏了。它不是我上传的相同图像。它是损坏的。

  2. 授权密钥经常过期。在我的情况下,我正在使用由gsutil生成的认证代码。


是的,这应该可以。您能否分享您的代码并详细说明“损坏”的含义? - jterrace
添加了一些代码,但遇到了一些具体问题。 - Gopinath
你为什么不使用 google-api-java-client - jterrace
我没有找到使用Google API Java客户端的示例代码。我对那一块不熟悉。你能帮我指明正确的方向吗? - Gopinath
那个问题的答案可以在这里找到:在Android中使用Google Cloud Storage JSON API - chelo_c
能否请Gopinath给我们一些指导?我们都被这个问题困扰着,而且缺乏文档。您是否有从Android上传图像/视频到Google Cloud Storage的步骤? - Jay
6个回答

16

1
嘿,我也想在Android中实现相同的功能,但您提供的代码是Java代码。您能否给出一些在Android中使用它的指导方针呢?以及我应该把cloudestorage.properties私钥文件放在哪里? - Zankhna
我在项目中创建了一个Base64编码的私钥内容字符串常量。然后,我通过解码此字符串来在应用程序私有文件中创建一个文件。稍后,我将指向此文件进行身份验证,这在我的情况下起作用。希望这可以帮助到您。 - Gopinath
@Gopinath,我解决了上述问题。但是我遇到了新的问题。当我执行mvn clean install时,出现以下错误:java.io.FileNotFoundException: var/e9-privatekey(没有这个文件或目录)。请给我任何建议。 - BABU K
@BABUK,请分享示例源代码,我无法使mvn clean install工作,因为我的项目是基于Gradle的。 - Cristiana Chavez
@Gopinath,当您说您正在通过解码字符串来创建文件时,它是否转换回.p12文件?您能否分享一下代码片段,展示.p12文件的编码部分转换为字符串,然后再将字符串转换回文件的过程? - maya
显示剩余3条评论

8

针对 Android 的修复:

Android Studio 配置:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/android-support-v4.jar')
    compile files('google-play-services.jar')
    compile 'com.wu-man:android-oauth-client:0.0.3'
    compile 'com.google.apis:google-api-services-storage:v1-rev17-1.19.0'
    compile(group: 'com.google.api-client', name: 'google-api-client', version:'1.19.0'){
        exclude(group: 'com.google.guava', module: 'guava-jdk5')
    }
}

Android清单文件:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

主要实现:

    new AsyncTask(){

        @Override
        protected Object doInBackground(Object[] params) {
            try {

                CloudStorage.uploadFile("bucket-xxx", "photo.jpg");

            } catch (Exception e) {
                if(DEBUG)Log.d(TAG, "Exception: "+e.getMessage());
                e.printStackTrace();
            }
            return null;
        }
    }.execute();

CloudStorage 类:

import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.StorageObject;

public static void uploadFile(String bucketName, String filePath)throws Exception {

    Storage storage = getStorage();
    StorageObject object = new StorageObject();
    object.setBucket(bucketName);
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,filePath);

    InputStream stream = new FileInputStream(file);

    try {
        String contentType = URLConnection.guessContentTypeFromStream(stream);
        InputStreamContent content = new InputStreamContent(contentType,stream);

        Storage.Objects.Insert insert = storage.objects().insert(bucketName, null, content);
        insert.setName(file.getName());
        insert.execute();

    } finally {
        stream.close();
    }
}

private static Storage getStorage() throws Exception {

    if (storage == null) {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        List<String> scopes = new ArrayList<String>();
        scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);

        Credential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(ACCOUNT_ID_PROPERTY) //Email                           
                .setServiceAccountPrivateKeyFromP12File(getTempPkc12File())
                .setServiceAccountScopes(scopes).build();

        storage = new Storage.Builder(httpTransport, jsonFactory,
            credential).setApplicationName(APPLICATION_NAME_PROPERTY)
            .build();
    }

    return storage;
}

private static File getTempPkc12File() throws IOException {
    // xxx.p12 export from google API console
    InputStream pkc12Stream = AppData.getInstance().getAssets().open("xxx.p12");
    File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
    OutputStream tempFileStream = new FileOutputStream(tempPkc12File);

    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = pkc12Stream.read(bytes)) != -1) {
        tempFileStream.write(bytes, 0, read);
    }
    return tempPkc12File;
}

你能告诉我什么是存储吗? - Bunny
嘿,伙计,你的代码不完整,能否请你编辑一下代码? :) - Jay
1
准备好了,我添加了缺失的导入(不是全部,但是最重要的)。 - Hpsaturn
我该如何检查文件是否成功上传到云端?除了列出存储桶文件之外,还有其他方法吗?我该如何获取从云端返回的响应? - Pravin Londhe
将p12文件与应用程序捆绑在一起是安全的吗?其他人能否使用相同的文件从您的存储中提取数据? - Harish Vishwakarma
显示剩余2条评论

3
这段代码对我来说非常有效,可以直接从Android上传文件到GCS。
File file = new File(Environment.getExternalStorageDirectory(), fileName);

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        FileBody filebody = new FileBody(file,ContentType.create(mimeType), file.getName());

        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();        
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("file", filebody);
        httppost.setEntity(multipartEntity.build());
        System.out.println( "executing request " + httppost.getRequestLine( ) );
        try {
            HttpResponse response = httpclient.execute( httppost );
            Log.i("response", response.getStatusLine().toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        httpclient.getConnectionManager( ).shutdown( );

MultipartEntityBuilder类不包含在Android标准库中,因此您需要下载httpclient并将其包含到您的项目中。


你的代码中HttpPost httppost = new HttpPost(url);这一行应该包含哪个URL?你是否将图片上传到了Google云存储? - BABU K
@BABUK 上传文件的URL可能看起来像这样 http://storage.googleapis.com/<你的存储桶名称>/你的文件名.jpg。请参考此文档 - Juniper
谢谢回复。我会尝试的。 - BABU K
你好,关于凭据方面怎么处理?你是在哪里进行身份验证的?我使用你的代码时收到了403禁止访问的错误...谢谢! - Tino

2

我尝试了以上所有答案,但都不能直接解决我的问题。以下是我所做的使其正常工作的步骤(只需根据上述评论进行编辑):

package  Your page name;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.StorageObject;

import java.io.File;
import java.io.*;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

 public class CloudStorage {

static Activity activity=null;
//https://dev59.com/eWMl5IYBdhLWcg3w76sI

static Storage storage=null;
public static void uploadFile(Activity activity2,String bucketName, String filePath)
{
    activity=activity2;
    try {
        Storage storage = getStorage();
        StorageObject object = new StorageObject();
        object.setBucket(bucketName);
        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(filePath);

        InputStream stream = new FileInputStream(file);

        try {
            Log.d("Alkamli","Test");
            String contentType = URLConnection.guessContentTypeFromStream(stream);
            InputStreamContent content = new InputStreamContent(contentType, stream);

            Storage.Objects.Insert insert = storage.objects().insert(bucketName, null, content);
            insert.setName(file.getName());
            insert.execute();

        } finally {
            stream.close();
        }
    }catch(Exception e)
    {
        class Local {}; Log.d("Alkamli","Sub: "+Local.class.getEnclosingMethod().getName()+" Error code: "+e.getMessage());

        e.printStackTrace();
    }
}

private static Storage getStorage() {

    try {

        if (storage == null)
        {
            HttpTransport httpTransport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            List<String> scopes = new ArrayList<String>();
            scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);

            Credential credential = new GoogleCredential.Builder()
                    .setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .setServiceAccountId("Service-Email-Address") //Email
                    .setServiceAccountPrivateKeyFromP12File(getTempPkc12File())
                    .setServiceAccountScopes(scopes).build();

            storage = new Storage.Builder(httpTransport, jsonFactory,
                    credential)
                    .build();
        }

        return storage;
    }catch(Exception e)
    {
        class Local {}; Log.d("Alkamli","Sub: "+Local.class.getEnclosingMethod().getName()+" Error code: "+e.getMessage());

    }
    Log.d("Alkamli","Storage object is null ");
    return null;
}

private static File getTempPkc12File() {
    try {
        // xxx.p12 export from google API console
        InputStream pkc12Stream = activity.getResources().getAssets().open("Service-key.p12");
        File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
        OutputStream tempFileStream = new FileOutputStream(tempPkc12File);
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = pkc12Stream.read(bytes)) != -1) {
            tempFileStream.write(bytes, 0, read);
        }
        return tempPkc12File;
    }catch(Exception e)
    {
        class Local {}; Log.d("Alkamli","Sub: "+Local.class.getEnclosingMethod().getName()+" Error code: "+e.getMessage());

    }
    Log.d("Alkamli"," getTempPkc12File is null");
    return null;
}
}

我只编辑了几行代码,使其能在我的项目中和gradle的依赖项中正常工作。你只需要这三个依赖项。(请注意,如果你使用所有谷歌的依赖项,可能会破坏整个项目,在我的情况下,一些Android的功能将不再起作用)

    compile 'com.google.api-client:google-api-client:1.20.0'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.20.0'
    compile 'com.google.apis:google-api-services-storage:v1-rev17-1.19.0' 

完整的项目适用于需要的人: https://github.com/Fahad-alkamli/Chat-app

2
@dude,我不是在问问题,只是提供了一个更新的解决方案。在写评论和给出负面反馈之前,你应该先阅读。 - Fahad Alkamli
@FahadAlkamli 我遇到了 com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found 的错误。 { "code" : 404, "errors" : [ { "domain" : "global", "message" : "Not Found", "reason" : "notFound" } ], "message" : "Not Found" } 有什么想法吗? - Ashish Jain
桶名称代表什么? - Taslim Oseni
1
@Taslim,我相信这是您在Google控制台上创建的存储桶名称。例如,您可以创建一个图像存储桶来存储图像等。 - Fahad Alkamli
1
@syed irfan 我真的不记得了,但这是你需要的完整项目在Github上:https://github.com/Fahad-alkamli/Chat-app - Fahad Alkamli
显示剩余2条评论

2
Hpsaturn的回答对我有帮助。他错过了回答一些问题。如何获取服务帐户ID和p12文件。要获取这两个文件,请打开console.developers.google.com并选择您的项目。启用Cloud Storage API。您会看到一个创建凭据的消息。进入API管理器中的凭据,通过选择服务帐户密钥来创建凭据,并按照图像中的详细信息进行操作。您将从此屏幕获得服务帐户ID和p12文件。

enter image description here

Hpsaturn也没有提到AppData,这是在清单中定义的自定义应用程序类。为了方便大家,我在这里附上完整的CloudStorage类。
package com.abc.xyz.utils;

import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.abc.xyz.app.AppController;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.StorageObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wjose on 8/20/2016.
 */
public class CloudStorage {

    private static final String TAG = "CloudStorage";

    public static void uploadFile(String bucketName, String name, Uri uri)throws Exception {

        Storage storage = getStorage();
        StorageObject object = new StorageObject();
        object.setBucket(bucketName);
        File sdcard = Environment.getExternalStorageDirectory();
        //File file = new File(sdcard,filePath);
        File file = new File(uri.getPath());

        InputStream stream = new FileInputStream(file);

        try {
            String contentType = URLConnection.guessContentTypeFromStream(stream);
            InputStreamContent content = new InputStreamContent(contentType,stream);

            Storage.Objects.Insert insert = storage.objects().insert(bucketName, null, content);
            insert.setName(name);
            StorageObject obj = insert.execute();
            Log.d(TAG, obj.getSelfLink());
        } finally {
            stream.close();
        }
    }

    static Storage storage = null;
    private static Storage getStorage() throws Exception {

        if (storage == null) {
            HttpTransport httpTransport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            List<String> scopes = new ArrayList<String>();
            scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);

            Credential credential = new GoogleCredential.Builder()
                    .setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .setServiceAccountId("myuser-801@xxxyyyzzz.iam.gserviceaccount.com") //Email
                    .setServiceAccountPrivateKeyFromP12File(getTempPkc12File())
                    .setServiceAccountScopes(scopes).build();

            storage = new Storage.Builder(httpTransport, jsonFactory,
                    credential).setApplicationName("MyApp")
                    .build();
        }

        return storage;
    }

    private static File getTempPkc12File() throws IOException {
        // xxx.p12 export from google API console
        InputStream pkc12Stream = MyApplication.getInstance().getAssets().open("xxxyyyzzz-0c80eed2e8aa.p12");
        File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
        OutputStream tempFileStream = new FileOutputStream(tempPkc12File);
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = pkc12Stream.read(bytes)) != -1) {
            tempFileStream.write(bytes, 0, read);
        }
        return tempPkc12File;
    }
}

btb,我在Gradle中只使用了以下依赖项:
``` compile 'com.google.apis:google-api-services-storage:+' ```

应用程序类 - Winster
@Winster,我应该在我的Android项目中的哪里添加已下载的.P12文件? - syed irfan
我遇到了这个错误,有人知道是怎么回事吗?com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request { "error" : "invalid_grant", "error_description" : "Robot is missing a project number." } - syed irfan

2

令人惊讶的是,上述解决方案都对我没用。原因在于,以上所有答案都使用.P12文件,而我拥有一个JSON文件作为API密钥。起初我不知道这两个不同的密钥,以为我做错了,经过一整天的查阅谷歌文档和stackoverflow,我终于能够上传到存储中。以上答案均未说明如何针对JSON文件进行操作,而代码略显简单,因此我发布此答案,希望能帮助某些人。

UploadFile.java

public class UploadFile {

    public static Storage setCredentials(InputStream credentialFile) {
        InputStream credentialsStream = null;;
        Credentials credentials = null;
        try {
            credentialsStream = credentialFile;
            credentials = GoogleCredentials.fromStream(credentialsStream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return StorageOptions.newBuilder()
                .setProjectId("YOUR_PROJECT_ID").setCredentials(credentials)
                .build().getService();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String transmitImageFile(Storage storage, String srcFileName, String newName) {
        File file = new File(srcFileName);
        byte[] fileContent = null;
        try {
            fileContent = Files.readAllBytes(file.toPath());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        if (fileContent == null)
            return null;
        if (fileContent.length == 0)
            return null;
        BlobInfo.Builder newBuilder = Blob.newBuilder(BucketInfo.of("YOUR_BUCKET_NAME"), newName);
        BlobInfo blobInfo = newBuilder.setContentType("image/png").build();
        Blob blob = storage.create(blobInfo, fileContent);
        String bucket = blob.getBucket();
        String contentType = blob.getContentType();
        Log.e("TAG", "transmitImageFile: "+contentType);
        System.out.println("File " + srcFileName + " uploaded to bucket " + bucket + " as " + newName);
        return newName;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private String currentPhotoPath;
    private String imageName;
    public static final int REQUEST_IMAGE_CAPTURE = 1;
    private File photoFile = null;
    private String[] permissions;
    public static final int PERMISSION_REQ_CODE = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView= findViewById(R.id.textView);
        permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION};
        PermissionsRequest();
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();
                ReadFromAsset();
            }
        });
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {
            photoFile = createImageFile();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this, getPackageName(), photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        String fileName = "temp";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg");

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        imageName = image.getName();

        return image;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Storage storage = UploadFile.setCredentials(getAssets().open("GoogleMapDemo.json"));
                        UploadFile.transmitImageFile(storage, currentPhotoPath, "sampleImage.jpg");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            Log.e("TAG", "ImagePath: " + currentPhotoPath);
            Log.e("TAG", "ImageName: " + imageName);
        }
    }

    private void PermissionsRequest() {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED) {
            AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
            builder1.setTitle("AAtten");
            builder1.setMessage("Permissions");
            builder1.setCancelable(false);
            builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    acceptPermissions();
                }
            });
            builder1.setNegativeButton("SAIR", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            //Creating dialog box
            AlertDialog alert1 = builder1.create();
            alert1.show();
        }
    }

    private void acceptPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[5]) != PackageManager.PERMISSION_GRANTED)
                requestPermissions(permissions, PERMISSION_REQ_CODE);
            else {
                if ((ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[1]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[2]) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), permissions[3]) != PackageManager.PERMISSION_GRANTED) || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[4]) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getApplicationContext(), permissions[5]) != PackageManager.PERMISSION_GRANTED)
                    requestPermissions(permissions, PERMISSION_REQ_CODE);
            }
        }
    }

    private void ReadFromAsset(){
        String string = "";
        try {
            //InputStream inputStream = new FileInputStream(String.valueOf(getAssets().open("key.p12")));
            InputStream inputStream = getAssets().open("GoogleMapDemo.json");
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            string = new String(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("TAG", "ReadFromAsset: "+string );
    }
}

现在在谷歌上搜索如何在应用程序中创建资产文件夹并将json密钥文件添加到该文件夹中。在onActivityResult类中,您将传递json文件的名称。
在UploadImage类中,在相应的字段中提供您的projectID和bucketName。您可以在那个json文件中找到projectID。
依赖项
android{
 packagingOptions{
        exclude 'META-INF/INDEX.LIST'
        exclude 'META-INF/DEPENDENCIES'
    }
}

    implementation platform('com.google.cloud:libraries-bom:16.2.1')
    implementation 'com.google.cloud:google-cloud-storage'
    implementation 'com.google.cloud:google-cloud-core:1.94.0'

Maifest
 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">

<application
  <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.personalgooglestoragecheck"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
</application

file-path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path
        name="my_images"
        path="/" />
    <external-path
        name="external"
        path="." />

    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

希望这能帮助到某些人。如有任何问题,请随时提问。
编辑1: 显然,Files.readAllBytes()是在Java 7中引入的,并且仅适用于Android API 26或更高版本。如果您想针对较低版本使用fileinputstream并删除所有@requireannotation标记。

这应该是被接受的答案。解释得很清楚。 - Parthi
太棒了!谢谢你的回答! - Febin Mathew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接