简体   繁体   English

使用 Java 将文件上传到 Cloud Storage for Firebase

[英]Upload file to Cloud Storage for Firebase with Java

I want to add files to my Google Cloud Storage (actually a Firebase bucket) using a java server.我想使用 java 服务器将文件添加到我的 Google Cloud Storage(实际上是一个 Firebase 存储桶)。

I am using this code i got on the internet:我正在使用我在互联网上获得的这段代码:

    // Authenticate using a service account
    Storage storage;
    try {
        storage = StorageOptions.newBuilder()
                .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream("C:/tmp/firebasekey.json")))
                .build()
                .getService();
        // The name for the new bucket
        String bucketName = "MinhaSaude";

        // Creates the new bucket
        Bucket bucket = storage.create(BucketInfo.of(bucketName));
        // Create blob
        BlobId blobId = BlobId.of("bucket", "blob_name");
        // Add metadata to the blob
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
        // Upload blob to GCS (same as Firebase Storage)
        Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes());

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

What I receive back is erros after Bucket bucket = storage.create(BucketInfo.of(bucketName));我收到的是Bucket bucket = storage.create(BucketInfo.of(bucketName));

Either "Invalid bucket name: 'MinhaSaude'" } “无效的存储桶名称:'MinhaSaude'”}

or "The account for bucket "minhasaude-api" has been disabled."或“存储桶“minhasaude-api”的帐户已被禁用。”

I cant find a bucketname that satisfies google.我找不到满足谷歌的存储桶名称。 I already uploaded a file to Firebase using browser and its uploading ok.我已经使用浏览器将文件上传到 Firebase,并且上传正常。

Try with my code, its works for me试试我的代码,它对我有用

String filename =  httpRequest.getFirstQueryParameter("name").get();
    String contentType =  httpRequest.getFirstQueryParameter("content-type").get();

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("key.json").getFile());
    FileInputStream serviceAccount = new FileInputStream(file);

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setStorageBucket("<you bucket name>")
            .build();

    FirebaseApp firebaseApp = FirebaseApp.initializeApp(options);
    Bucket bucket = StorageClient.getInstance(firebaseApp).bucket();


    Storage storage = StorageOptions.newBuilder().setProjectId("firebaseId")
            .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(file)))
            .build()
            .getService();
    file = new File(classLoader.getResource("jar-loading.gif").getFile());

    InputStream inputStream = new FileInputStream(file);
    BlobInfo blobInfo = BlobInfo.newBuilder(bucket.getName(), filename)
            .setContentType(contentType).build();

    try (WriteChannel writer = storage.writer(blobInfo)) {
        byte[] buffer = new byte[1024];
        int limit;
        try {
            while ((limit = inputStream.read(buffer)) >= 0) {
                writer.write(ByteBuffer.wrap(buffer, 0, limit));
            }

        } catch (Exception ex) {
            // handle exception
        } finally {
            writer.close();
        }
    }

With that code I could upload gif file from my project to firebase storage.使用该代码,我可以将 gif 文件从我的项目上传到 Firebase 存储。 Make change to use it进行更改以使用它

Is it possible that there are buckets that you have created previously?是否可能有您之前创建的存储桶? Try a random string of letters and see if that works.尝试一个随机的字母串,看看是否有效。

Alternately, one can only create GCS buckets when billing has been enabled for your GCS project.或者,只有在为您的 GCS 项目启用计费后,才能创建 GCS 存储桶。 Have you set up your project with a credit card and whatnot?您是否使用信用卡等设置了您的项目?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM