首页 文章

Java Google Cloud Storage上传媒体链接为null,但图片上传

提问于
浏览
3

我正在尝试将图片上传到Google Cloud 端存储中的现有存储分区 . 当我去检查时,图像文件成功上传,
但是返回的下载网址是 null

代码

private String uploadImage(File filePath, String blobName, File uploadCreds) throws FileNotFoundException, IOException{


   Storage storage = StorageOptions.newBuilder().setProjectId("myProjectId")
                .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(uploadCreds)))
                .build()
                .getService();

                    String bucketName = "myBucketName"; 
                    Bucket bucket = storage.get(bucketName);
        BlobId blobId = BlobId.of(bucket.getName(), blobName);
        InputStream inputStream = new FileInputStream(filePath);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();


    try (WriteChannel writer = storage.writer(blobInfo)) {
        byte[] buffer = new byte[1024];
        int limit;
        try {
            while ((limit = inputStream.read(buffer)) >= 0) {
                writer.write(ByteBuffer.wrap(buffer, 0, limit));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            writer.close();

        }
                     System.out.println("Image URL : " + blobInfo.getMediaLink());
                     System.out.println("Blob URL : " + blobInfo.getSelfLink());
                     return blobInfo.getMediaLink();
    }


}

filePath是图像文件
blobName是一个随机图像名称
uploadCreds是我的credintials.json文件

为什么 blobInfo.getMediaLink()blobInfo.getSelfLink() 返回 null
我究竟做错了什么?

2 回答

  • 3

    这是我的代码完美无缺

    @RestController @RequestMapping(“/ api”)公共类CloudStorageHelper {

    Credentials credentials = GoogleCredentials.fromStream(new FileInputStream("C:\\Users\\sachinthah\\Downloads\\MCQ project -1f959c1fc3a4.json"));
        Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
    
        public CloudStorageHelper() throws IOException {
        }
    
    
        @SuppressWarnings("deprecation")
        @RequestMapping(method = RequestMethod.POST, value = "/imageUpload112")
        public String uploadFile(@RequestParam("fileseee")MultipartFile fileStream)
                throws IOException, ServletException {
            BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
            String bucketName = "mcqimages";
            checkFileExtension(fileStream.getName());
            DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
            DateTime dt = DateTime.now(DateTimeZone.UTC);
    
            String fileName = fileStream.getOriginalFilename()  ;
    
            BlobInfo blobInfo =
                    storage.create(
                            BlobInfo
                                    .newBuilder(bucketName, fileName)
                                    .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
                                    .build(),
                            fileStream.getInputStream()
                    );
            System.out.println(blobInfo.getMediaLink());
    
            //sachintha added a comma after the link to identify the link that get generated
               return blobInfo.getMediaLink()+",";
    
        }
    
    
    private void checkFileExtension(String fileName) throws ServletException {
        if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
            String[] allowedExt = {".jpg", ".jpeg", ".png", ".gif"};
            for (String ext : allowedExt) {
                if (fileName.endsWith(ext)) {
                    return;
                }
            }
            throw new ServletException("file must be an image");
        }
    }
    
  • 2

    答案非常简单,我只是摆脱了手动上传方法并使用了内置的创建blob .

    private String uploadImage(File filePath, String blobName, File uploadCreds) throws FileNotFoundException, IOException{
    
    
       Storage storage = StorageOptions.newBuilder().setProjectId("porjectId")
                    .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(uploadCreds)))
                    .build()
                    .getService();
    
                        String bucketName = "bucketName"; 
                        Bucket bucket = storage.get(bucketName);
            BlobId blobId = BlobId.of(bucket.getName(), blobName);
            InputStream inputStream = new FileInputStream(filePath);
            BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();
    
    
                        Blob blob = storage.create(blobInfo, inputStream);
    
    
                         System.out.println("Image URL : " +  blob.getMediaLink());
    
               return  blob.getMediaLink();
    
    
    
    }
    

相关问题