如何使用Java将图像/文件上传到Firebase存储?

时间:2018-10-22 11:26:41

标签: java rest firebase firebase-storage

我正在使用需要使用Java将图像/文件上传到Firebase存储并将其作为API公开的功能。我已经在angular 4打字稿中实现了此功能。但是现在我需要将此方法用作Java Rest API,以便我的对等方也可以使用相同的方法,而不必编写新的方法。那么,是否有任何API或方法可将映像写入Firebase存储?

3 个答案:

答案 0 :(得分:2)

如果Java项目在受信任的环境(例如其开发机,您控制的服务器或Cloud Functions)中运行,则他们可以使用Firebase Admin SDK来访问Cloud Storage。

有关如何开始的信息,请参见Firebase Admin SDK documentation,然后是Google Cloud Storage documentation for Java clients,以获取更多信息。具体看一下sample of uploading a file in Java

BlobId blobId = BlobId.of("bucket", "blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));

答案 1 :(得分:2)

尝试一下:

FirebaseOptions options = FirebaseOptions.builder()
                    .setCredentials(credential)
                    .setDatabaseUrl(projectUrl)
                    .setStorageBucket("YOUR BUCKET LINK")
                    .build();

    FirebaseApp fireApp = FirebaseApp.initializeApp(options);

    StorageClient storageClient = StorageClient.getInstance(fireApp);
            InputStream testFile = new FileInputStream("YOUR FILE PATH");
            String blobString = "NEW_FOLDER/" + "FILE_NAME.EXT";        

    storageClient.bucket().create(blobString, testFile , Bucket.BlobWriteOption.userProject("YOUR PROJECT ID"));

答案 2 :(得分:0)

String blobString = DIR + fileIdWithExtension;
Blob blob = storageClient.bucket().create(blobString, file.getInputStream(), Bucket.BlobWriteOption.userProject(PROJECT_ID));

但是请记住,您应该初始化firebase。例如

   private FirebaseApp initFirebase() {
        FileInputStream serviceAccount;
        try {
            serviceAccount = new FileInputStream(fileUploadPath);
        } catch (FileNotFoundException e) {
            throw new FileStorageException(ErrorMessage.FILE_NOT_FOUND + "firebaseConfig.json");
        }
        FirebaseOptions options;
        try {
            options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                    .setStorageBucket(BUCKET_NAME)
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
            throw new FailedToSetCredentialsException(ErrorMessage.COULD_NOT_SET_CREDENTIALS);
        }

        return FirebaseApp.initializeApp(options);
    }