首页 > 解决方案 > 无法使用 Spring Boot 在 Firebase 存储上预览上传的图像

问题描述

我正在尝试使用spring boot在firebase存储中上传文件,下面是我的一段代码,我的文件正在上传,但我尝试从firebase UI预览它是预览没有加载(请参考图片)在此处输入图像描述

,而当我从firebase UI的上传文件选项上传相同的文件时,它正在预览。请帮助我解决这个问题。

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);
    }

标签: javaspringfirebasespring-bootfirebase-storage

解决方案


当您通过 firebase UI 上传文件时,会自动生成访问令牌,但不会为通过 Java 上传的文件生成访问令牌。

您需要创建一个 Map 来定义一些元数据。

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

并将其传递到您的 blobInfo 中:

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

您的代码应如下所示:

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);
    }

推荐阅读