【问题标题】:Unable to preview uploaded image on firebase storage using spring boot无法使用 Spring Boot 在 Firebase 存储上预览上传的图像
【发布时间】:2020-12-22 10:29:00
【问题描述】:

我正在尝试使用 Spring Boot 在 Firebase 存储中上传文件,下面是我的一段代码,我的文件正在上传,但我尝试从 Firebase UI 预览它是预览未加载(请参考图片)@987654321 @

,当我从 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);
    }

【问题讨论】:

  • 请点击“文件位置”中的“创建新访问令牌”选项以验证您需要访问令牌来预览图片。

标签: java spring firebase spring-boot firebase-storage


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2021-01-25
    • 2016-12-18
    • 2021-04-27
    • 2018-12-21
    • 1970-01-01
    • 2021-08-11
    • 2022-07-28
    • 2020-03-05
    相关资源
    最近更新 更多