Java Spring Boot中的Firebase上传 [英] Firebase Upload in Java Spring Boot

查看:86
本文介绍了Java Spring Boot中的Firebase上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件上传到Java Spring Boot中的Firebase存储中.我在网上查看了Stack Overflow和其他地方,但尚未找到有效的解决方案.请先帮助并谢谢!!

I'm trying upload a file to Firebase storage in Java Spring Boot. I have looked on Stack Overflow and elsewhere online but have not found a working solution yet. 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

如果删除 UTF_8 部分,则会出现以下错误:

If I remove the UTF_8 part, I get the following error:

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=zh_

Note you need to download Firebase config file and store it as "firebase.json" under the src/main/resources folder. https://support.google.com/firebase/answer/7015592?hl=en

还需要添加Maven依赖项:

Also you need to add the Maven dependency:

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

这篇关于Java Spring Boot中的Firebase上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆