java - Java Spring Boot 中的 Firebase 上传

标签 java firebase firebase-storage

我正在尝试将文件上传到 Java Spring Boot 中的 Firebase 存储。我查看了 Stack Overflow 和其他在线内容,但尚未找到可行的解决方案。请帮助并提前致谢!

到目前为止,我有以下代码,它基于 this question 的代码:

// Input Firebase credentials:
FileInputStream serviceAccount = new FileInputStream("{{path to the keys}}");
FirebaseOptions options = new FirebaseOptions.Builder()
                  .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                  .setDatabaseUrl("{{url}}")
                  .build();
FirebaseApp.initializeApp(options);

// Other Firebase variables:
FirebaseApp storage = FirebaseApp.getInstance();

// Upload to Firebase:
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));

但是,我无法运行它,因为出现以下错误:

UTF_8 cannot be resolved to a variable

如果我删除 UTF_8 部分,我会收到以下错误:

The method create(BlobInfo, byte[]) is undefined for the type Object

最佳答案

你可以试试这个:

  1. 创建一个类以在您的 API 中将其公开为网络服务:
import com.yourcompany.yourproject.services.FirebaseFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ResourceController {
    @Autowired
    private FirebaseFileService firebaseFileService;
    
    @PostMapping("/api/v1/test")
    public ResponseEntity create(@RequestParam(name = "file") MultipartFile file) {
        try {
            String fileName = firebaseFileService.saveTest(file);
            // do whatever you want with that
        } catch (Exception e) {
        //  throw internal error;
        }
        return ResponseEntity.ok().build();
    }
}
  1. 创建服务以将图像上传到 Firebase 存储。
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.firebase.cloud.StorageClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
import com.google.cloud.storage.StorageOptions;
import java.util.HashMap;
import java.util.Map;

@Service
public class FirebaseFileService {

    private Storage storage;

    @EventListener
    public void init(ApplicationReadyEvent event) {
        try {
            ClassPathResource serviceAccount = new ClassPathResource("firebase.json");
            storage = StorageOptions.newBuilder().
                    setCredentials(GoogleCredentials.fromStream(serviceAccount.getInputStream())).
                    setProjectId("YOUR_PROJECT_ID").build().getService();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String saveTest(MultipartFile file) throws IOException{
        String imageName = generateFileName(file.getOriginalFilename());
        Map<String, String> map = new HashMap<>();
        map.put("firebaseStorageDownloadTokens", imageName);
        BlobId blobId = BlobId.of("YOUR_BUCKET_NAME", imageName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId)
                .setMetadata(map)
                .setContentType(file.getContentType())
                .build();
        storage.create(blobInfo, file.getInputStream());
        return imageName;
    }
    
    private String generateFileName(String originalFileName) {
        return UUID.randomUUID().toString() + "." + getExtension(originalFileName);
    }

    private String getExtension(String originalFileName) {
        return StringUtils.getFilenameExtension(originalFileName);
    }
}

请注意,您需要下载 Firebase 配置文件并将其作为“firebase.json”存储在 src/main/resources 文件夹下。 https://support.google.com/firebase/answer/7015592?hl=en

还需要添加 Maven 依赖:

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>6.14.0</version>
</dependency>

关于java - Java Spring Boot 中的 Firebase 上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55231615/

相关文章:

Java 将考试成绩写入文件

java - Weblogic Server 11g 上的自定义线程

java - 如何通过 Java 在 Eclipse 中使用 Taglet 或 Tag

node.js - NodeJS 中的 Firebase 事务总是运行 3 次?

javascript - 使用 Firebase 更新文档字段时使用 Object.assign

ios - 在 Swift 中下载图片时,Firebase 引用为 'variable not available'

java - 方法的泛型重载 - 解决方法

javascript - node.js:遍历嵌套的 firebase JSON 树

javascript - 将 firebase-messaging-sw.js deps 与 Webpack 捆绑在一起

ios - 火力地堡存储 : How to Delete Directory