Unable to preview uploaded image on firebase storage using spring boot

Viewed 425

I am trying to upload file in firebase storage using spring boot, below is my piece of code, my file is getting uploaded but i try to preview it from firebase UI is preview is not loading(pls refer the image) enter image description here

, while when i am uploading same file from Upload file option from firebase UI then it is previewing fine. Pls assist me with this problem.

public FileRequest uploadImage(FileRequest fileRequest, MultipartFile file) throws IOException {
        if(file.isEmpty()){
            throw new NullPointerException("No File Found..");
        }
        byte[] fileByteArray = file.getBytes();
        ClassPathResource resource = new ClassPathResource("firebase.json");
        Storage storage = StorageOptions
                .newBuilder()
                .setCredentials(ServiceAccountCredentials
                        .fromStream(resource.getInputStream()))
                .build()
                .getService();
        BlobId blobId = BlobId.of(FileConstant.bucketName,fileRequest.getUploadContext() + "/" + fileRequest.getFileId());
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(fileRequest.getMimeType()).build();
        storage.create(blobInfo,fileByteArray);
        return fileDAO.uploadFile(fileRequest);
    }
1 Answers

When you upload files via firebase UI will have an access token automatically generated but no for files uploaded via Java.

You need to create a Map to define some metadata.

Map<String, String> map = new HashMap<>();
map.put("firebaseStorageDownloadTokens", imageName);

And pass it into your blobInfo:

BlobInfo blobInfo = BlobInfo.newBuilder(blobId)
                .setMetadata(map)
                .setContentType(file.getContentType())
                .build();

Your code should look like this:

public FileRequest uploadImage(FileRequest fileRequest, MultipartFile file) throws IOException {
        if(file.isEmpty()){
            throw new NullPointerException("No File Found..");
        }
        byte[] fileByteArray = file.getBytes();
        ClassPathResource resource = new ClassPathResource("firebase.json");
        Storage storage = StorageOptions
                .newBuilder()
                .setCredentials(ServiceAccountCredentials
                        .fromStream(resource.getInputStream()))
                .build()
                .getService();
        String imageName = fileRequest.getUploadContext() + "/" + fileRequest.getFileId();
        Map<String, String> map = new HashMap<>();
        map.put("firebaseStorageDownloadTokens", imageName);
        BlobId blobId = BlobId.of(FileConstant.bucketName, imageName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setMetadata(map).setContentType(fileRequest.getMimeType()).build();
        storage.create(blobInfo,fileByteArray);
        return fileDAO.uploadFile(fileRequest);
    }
Related