不足为奇的是,上述解决方案都不适合我。原因,在所有上述答案中,他们使用的是 .P12 文件,而我得到了一个 JSON 文件作为 api 密钥。起初我不知道这两个不同的键,我认为我做错了,经过一天紧张的谷歌文档,stackoverflow 我终于能够上传到存储。以上答案都没有显示如何为 JSON 文件执行此操作,并且代码有点简单,所以我发布了这个答案,希望这对某人有所帮助:
上传文件.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.file 中找到 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'
迈费斯特
<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
文件路径.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 标记。