Firebase Upload in Java Spring Boot

蓝咒 提交于 2021-02-08 20:59:37

问题


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

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

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

回答1:


You can try this:

  1. Create a class to expose it as a web service in your 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. Create a service to upload the image to firebase storage.
@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. https://support.google.com/firebase/answer/7015592?hl=en

Also you need to add the Maven dependency:

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


来源:https://stackoverflow.com/questions/55231615/firebase-upload-in-java-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!