我想开发一个java应用程序(用于个人电脑),可以将任何图片上传到Google云端存储。虽然我整个晚上都在寻找解决方案,但我没有任何线索如何开始。您是否有人将图像上传到Google云端存储?是否有更好的Google云端存储替代方案?
答案 0 :(得分:6)
使用Google Cloud有一个可爱的Java API,包括存储:http://googlecloudplatform.github.io/google-cloud-java/0.10.0/index.html
以下是使用此库上传和下载文件的示例桌面应用程序:https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java
Google Cloud Storage提供了大量文档,指南和教程。以下是它的全部内容:https://cloud.google.com/storage/docs/
答案 1 :(得分:1)
@Override
public String uploadImage(String fileName , String filePath,String fileType) throws IOException {
Bucket bucket = getBucket("sample-bucket");
InputStream inputStream = new FileInputStream(new File(filePath));
Blob blob = bucket.create(fileName, inputStream, fileType);
log.info("Blob Link:"+blob.getMediaLink());
return blob.getMediaLink();
}
private Bucket getBucket(String bucketName) throws IOException {
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(CREDENTIALS_PATH))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
Bucket bucket = storage.get(bucketName);
if (bucket == null) {
throw new IOException("Bucket not found:"+bucketName);
}
return bucket;
}
CREDENTIALS_PATH,在设置服务帐户时下载,请确保用户有权将存储桶中的图像上传。
答案 2 :(得分:1)
您可以公开文件,然后Blob的媒体链接可以在任何地方访问。
https://cloud.google.com/storage/docs/access-control/making-data-public
这是我的解决方法。
try {
FileInputStream serviceAccount =
new FileInputStream("firebaseKey/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://xxxxx.firebaseio.com")
.build();
FirebaseApp fireApp = FirebaseApp.initializeApp(options);
StorageClient storageClient = StorageClient.getInstance(fireApp);
InputStream testFile = new FileInputStream(file.getPath());
String blobString = "NEW_FOLDER/" + "FILE_NAME.jpg";
Blob blob = storageClient.bucket("xxxxxx.appspot.com")
.create(blobString, testFile , Bucket.BlobWriteOption.userProject("xxxxxxx"));
blob.getStorage().createAcl(blob.getBlobId(), Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
System.out.println(blob.getMediaLink());
} catch (Exception e){
e.printStackTrace();
}