It's time to change the downloaded file name in the Google Cloud Storage using java(BlobstoreService). Is there any provision in the BlobstoreService to change the file name before downloading that file? Is there any useful API for changing the filename? Here the thing that happens is, when I save a file in the GCS, it will generate a blob key. And the file type also changes in the Google cloud storage. Now I just want to change the file name before it downloads, and also the type of the file.
You can rename a file by reading the file in and saving it with the new name. Here is some sample code to get you started, you will likely need to add your own delete function in order to delete the old file:
public void moveFile(String fileName, String bucket, String newFilename, String contentType) throws IOException {
byte[] bytes = loadFile(bucket, fileName);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
saveToGcs(bucket, fileName, in, contentType);
}
public byte[] loadFile(String bucket, String fileName) throws IOException {
GcsFilename gcsFileName = new GcsFilename(bucket, fileName);
GcsInputChannel readChannel = gcsService.openReadChannel(gcsFileName, 0);
InputStream in = Channels.newInputStream(readChannel);
return IOUtils.toByteArray(in);
}
private void saveToGcs(String bucket, String filename, InputStream inputStream, String mimeType) throws IOException {
GcsFilename gcsFilename = new GcsFilename(bucket, filename);
GcsFileOptions options = new GcsFileOptions.Builder().mimeType(mimeType).acl("public-read").build();
GcsOutputChannel writeChannel = gcsService.createOrReplace(gcsFilename, options);
BufferedOutputStream outputStream = new BufferedOutputStream(Channels.newOutputStream(writeChannel));
IOUtils.copy(inputStream, outputStream);
outputStream.close();
writeChannel.close();
}