2
votes

I am going to upload either CSV file or PDF file to Google Cloud Storage using this code:

public static String uploadFile(String fileName, String fileLocation, final String bucketName) throws IOException {
      DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
      DateTime dt = DateTime.now(DateTimeZone.UTC);
      String dtString = dt.toString(dtf);
      fileName += dtString;

      // The InputStream is closed by default, so we don't need to close it here
      // Read InputStream into a ByteArrayOutputStream.

      File file = new File(fileLocation);

      InputStream is = new FileInputStream(file);
      ByteArrayOutputStream os = new ByteArrayOutputStream();
      byte[] readBuf = new byte[4096];
      while (is.available() > 0) {
        int bytesRead = is.read(readBuf);
        os.write(readBuf, 0, bytesRead);
      }

      is.close();

      // Convert ByteArrayOutputStream into byte[]
      BlobInfo blobInfo =
          storage.create(
              BlobInfo
                  .newBuilder(bucketName, fileName)
                  // Modify access list to allow all users with link to read file
                  .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
                  .build(),
              os.toByteArray());
      // return the public download link
      return blobInfo.getMediaLink();
    }

When I download the uploaded file, if it is a CSV file, it is fine, but when I download the PDF file, it always show a blank page. And it is also shown a blank page on the console itself.

1

1 Answers

2
votes

Do not use available() as it just provides a means to prevent blocking, trying to read more than the OS file buffer already has read. It can be 0 at any time, pending following physical reads.

  while (true) {
    int bytesRead = is.read(readBuf);
    if (bytesRead < 0) {
        break;
    }
    os.write(readBuf, 0, bytesRead);
  }

Or simply use:

  Path file = Paths.get(fileLocation);
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  Files.copy(file, os);