无法使用spring boot在firebase存储上预览上载的图像

ojsjcaue  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(245)

我试图上传文件在firebase存储使用 Spring 启动,下面是我的一段代码,我的文件正在上传,但我试图预览它从firebase用户界面是预览没有加载(请参考图片)

,当我从firebase用户界面上传同一个文件时,上传文件选项可以很好的预览。请帮我解决这个问题。

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

n1bvdmb61#

当您通过firebase上传文件时,ui将自动生成一个访问令牌,但不会为通过java上传的文件生成访问令牌。
您需要创建一个Map来定义一些元数据。

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

把它传给你的女朋友:

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

相关问题