Reputation: 155
I am working in a functionality where i need to upload an Image/File to firebase storage using java and expose it as an API. I have already achieved this functionality in angular 4 typescript. But now i need this method as an Java Rest API, so that my peer can also consume the same method instead of writing a new one. So is there any API or methods to write the image to firebase storage ?
Upvotes: 5
Views: 10568
Reputation: 2111
If you are using Spring Boot, you can try this:
import com.yourcompany.yourproject.services.FirebaseFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class ResourceController {
@Autowired
private FirebaseFileService firebaseFileService;
@PostMapping("/api/v1/test")
public ResponseEntity create(@RequestParam(name = "file") MultipartFile file) {
try {
String fileName = firebaseFileService.saveTest(file);
// do whatever you want with that
} catch (Exception e) {
// throw internal error;
}
return ResponseEntity.ok().build();
}
}
@Service
public class FirebaseFileService {
private Storage storage;
@EventListener
public void init(ApplicationReadyEvent event) {
try {
ClassPathResource serviceAccount = new ClassPathResource("firebase.json");
storage = StorageOptions.newBuilder().
setCredentials(GoogleCredentials.fromStream(serviceAccount.getInputStream())).
setProjectId("YOUR_PROJECT_ID").build().getService();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String saveTest(MultipartFile file) throws IOException{
String imageName = generateFileName(file.getOriginalFilename());
Map<String, String> map = new HashMap<>();
map.put("firebaseStorageDownloadTokens", imageName);
BlobId blobId = BlobId.of("YOUR_BUCKET_NAME", imageName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId)
.setMetadata(map)
.setContentType(file.getContentType())
.build();
storage.create(blobInfo, file.getInputStream());
return imageName;
}
private String generateFileName(String originalFileName) {
return UUID.randomUUID().toString() + "." + getExtension(originalFileName);
}
private String getExtension(String originalFileName) {
return StringUtils.getFilenameExtension(originalFileName);
}
}
Note you need to download Firebase config file and store it as "firebase.json" under the src/main/resources folder. https://support.google.com/firebase/answer/7015592?hl=en
Also you need to add the Maven dependency:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.14.0</version>
</dependency>
Upvotes: 2
Reputation: 3
String blobString = DIR + fileIdWithExtension;
Blob blob = storageClient.bucket().create(blobString, file.getInputStream(), Bucket.BlobWriteOption.userProject(PROJECT_ID));
But keep in mind that you should initialize firebase. For example
private FirebaseApp initFirebase() {
FileInputStream serviceAccount;
try {
serviceAccount = new FileInputStream(fileUploadPath);
} catch (FileNotFoundException e) {
throw new FileStorageException(ErrorMessage.FILE_NOT_FOUND + "firebaseConfig.json");
}
FirebaseOptions options;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setStorageBucket(BUCKET_NAME)
.build();
} catch (IOException e) {
e.printStackTrace();
throw new FailedToSetCredentialsException(ErrorMessage.COULD_NOT_SET_CREDENTIALS);
}
return FirebaseApp.initializeApp(options);
}
Upvotes: 0
Reputation: 170
Try this:
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(credential)
.setDatabaseUrl(projectUrl)
.setStorageBucket("YOUR BUCKET LINK")
.build();
FirebaseApp fireApp = FirebaseApp.initializeApp(options);
StorageClient storageClient = StorageClient.getInstance(fireApp);
InputStream testFile = new FileInputStream("YOUR FILE PATH");
String blobString = "NEW_FOLDER/" + "FILE_NAME.EXT";
storageClient.bucket().create(blobString, testFile , Bucket.BlobWriteOption.userProject("YOUR PROJECT ID"));
Upvotes: 4
Reputation: 598740
If the Java project is running in a trusted environment (such as their development machine, a server you control, or Cloud Functions), they can use the Firebase Admin SDK to access Cloud Storage.
See the Firebase Admin SDK documentation on how to get started, and then the Google Cloud Storage documentation for Java clients for more. Specifically have a look at the sample of uploading a file in Java:
BlobId blobId = BlobId.of("bucket", "blob_name"); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
Upvotes: 1