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

时间:2018-03-03 08:51:25

标签: java google-cloud-platform google-cloud-storage

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

CODE

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
我做错了什么?

3 个答案:

答案 0 :(得分:3)

这是我的代码,可以很好地工作

@RestController
@RequestMapping("/api")
public class 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 = 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");
    }
}

答案 1 :(得分: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();



}

答案 2 :(得分:0)

如果要将其存储在特殊文件夹中,请获取blobinfo.name()并在其后附加“ /”。例如,如果temp.jpg需要与日期文件夹一起存储。从日期对象获取日期,并使用日期格式器对其进行格式化,并在其前面加上

blobinfo.name()= date +“ /” + blobinfo.name();

将按日期对所有图像进行分类。