After storing image file in Google Cloud Storage Bucket, it show the lists of all files with size as "0 bytes"

909 views Asked by At

Steps I've followed:

1) Store the images in Blobstore.(This is necessary) 2) Fetch the images from blobstore and save it in GCS bucket.

If I store the image file directly to GCS bucket then it works fine. But I want to fetch it from Blobstore.

Map<String, List<BlobInfo>> blobsData = blobstoreService.getBlobInfos(req);
     for (String key : blobsData.keySet())
         {
             for(BlobInfo blob:blobsData.get(key))
             {
  byte[] b = new byte[(int)blob.getSize()];
  BlobstoreInputStream in = new BlobstoreInputStream(blob.getBlobKey());
  in.read(b);

  GcsService gcsService = GcsServiceFactory.createGcsService();
  GcsFilename filename = new GcsFilename("casfilestorage", blob.getFilename());
  GSFileOptionsBuilder builder = new GSFileOptionsBuilder()
  .setAcl("public_read")
  .setBucket(BUCKET_NAME)
  .setKey(blob.getFilename())
  .setMimeType(blob.getContentType());

  AppEngineFile writableFile = fileService.createNewGSFile(builder.build());
  boolean lock = true;

  writeChannel = fileService.openWriteChannel(writableFile, lock);
  os = Channels.newOutputStream(writeChannel);

  UploadOptions uploadOptions = UploadOptions.Builder.withGoogleStorageBucketName("casgaestorage");
  //String uploadUrl = blobstoreService.createUploadUrl("/serve", uploadOptions);

  os.close();
  writeChannel.closeFinally();

  in.close();
             }
         }
1

There are 1 answers

0
Harshal Patil On

Refer below code, Just pass your byte[] to write method:

GcsService f_ObjGcsService = GcsServiceFactory.createGcsService();

GcsFilename f_ObjFilename = new GcsFilename("BUCKET NAME", "FileName");
GcsFileOptions f_ObjOptions = new GcsFileOptions.Builder()
.mimeType("Content Type")
.acl("public-read")
.build();

GcsOutputChannel f_ObjWriteChannel = f_ObjGcsService.createOrReplace("Filename", f_ObjOptions);

PrintWriter f_ObjWriter = new PrintWriter(Channels.newWriter(f_ObjWriteChannel, "UTF8"));

f_ObjWriter.flush();

f_ObjWriteChannel.waitForOutstandingWrites();

f_ObjWriteChannel.write(ByteBuffer.wrap("Byte Array that u get from blob"));

f_ObjWriteChannel.close();