简体   繁体   English

Java Spring Boot 中的 Firebase 上传

[英]Firebase Upload in Java Spring Boot

I'm trying upload a file to Firebase storage in Java Spring Boot.我正在尝试在 Java Spring Boot 中将文件上传到 Firebase 存储。 I have looked on Stack Overflow and elsewhere online but have not found a working solution yet.我在网上查看了 Stack Overflow 和其他地方,但还没有找到可行的解决方案。 Please help and thanks in advance!请帮助并提前致谢!

So far I have the following code below, which is based on the code of 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));

However, I cannot run this, as I get the following error:但是,我无法运行它,因为我收到以下错误:

UTF_8 cannot be resolved to a variable

If I remove the UTF_8 part, I get the following error:如果删除UTF_8部分, UTF_8出现以下错误:

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

You can try this:你可以试试这个:

  1. Create a class to expose it as a web service in your API:创建一个类以将其公开为 API 中的 Web 服务:
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. Create a service to upload the image to firebase storage.创建一个服务以将图像上传到 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);
    }
}

Note you need to download Firebase config file and store it as "firebase.json" under the src/main/resources folder.请注意,您需要下载 Firebase 配置文件并将其存储为 src/main/resources 文件夹下的“firebase.json”。 https://support.google.com/firebase/answer/7015592?hl=en https://support.google.com/firebase/answer/7015592?hl=en

Also you need to add the Maven dependency:您还需要添加 Maven 依赖项:

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

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

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