Skip to content

Instantly share code, notes, and snippets.

@Ikhiloya
Last active July 20, 2020 23:10
Show Gist options
  • Save Ikhiloya/3378a063977bab706dd4522d467a30e7 to your computer and use it in GitHub Desktop.
Save Ikhiloya/3378a063977bab706dd4522d467a30e7 to your computer and use it in GitHub Desktop.
Storage Strategy for firebase upload and download
@Service
public class FirebaseStorageStrategy implements StorageStrategy {
private final Logger log = LoggerFactory.getLogger(FirebaseStorageStrategy.class);
private final Environment environment;
private StorageOptions storageOptions;
private String bucketName;
private String projectId;
public FirebaseStorageStrategy(Environment environment) {
this.environment = environment;
}
@PostConstruct
private void initializeFirebase() throws Exception {
bucketName = environment.getRequiredProperty("FIREBASE_BUCKET_NAME");
projectId = environment.getRequiredProperty("FIREBASE_PROJECT_ID");
FileInputStream serviceAccount =
new FileInputStream("/home/user/Downloads/service-account-file.json");
this.storageOptions = StorageOptions.newBuilder()
.setProjectId(projectId)
.setCredentials(GoogleCredentials.fromStream(serviceAccount)).build();
}
public String[] uploadFile(MultipartFile multipartFile) throws IOException {
File file = convertMultiPartToFile(multipartFile);
Path filePath = file.toPath();
String objectName = generateFileName(multipartFile);
Storage storage = storageOptions.getService();
BlobId blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
Blob blob = storage.create(blobInfo, Files.readAllBytes(filePath));
log.info("File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
return new String[]{"fileUrl", objectName};
}
@Override
public ResponseEntity<Object> downloadFile(String fileName, HttpServletRequest request) throws Exception {
Storage storage = storageOptions.getService();
Blob blob = storage.get(BlobId.of(bucketName, fileName));
ReadChannel reader = blob.reader();
InputStream inputStream = Channels.newInputStream(reader);
byte[] content = null;
log.info("File downloaded successfully.");
content = IOUtils.toByteArray(inputStream);
final ByteArrayResource byteArrayResource = new ByteArrayResource(content);
return ResponseEntity
.ok()
.contentLength(content.length)
.header("Content-type", "application/octet-stream")
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.body(byteArrayResource);
}
private File convertMultiPartToFile(MultipartFile file) throws IOException {
File convertedFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
FileOutputStream fos = new FileOutputStream(convertedFile);
fos.write(file.getBytes());
fos.close();
return convertedFile;
}
private String generateFileName(MultipartFile multiPart) {
return new Date().getTime() + "-" + Objects.requireNonNull(multiPart.getOriginalFilename()).replace(" ", "_");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment