如何将非Android Java应用连接至Firebase Storage并上传文件?
Hey there! I’ve been stuck trying to connect a Java app to Firebase Storage too, so I feel your pain. Let’s walk through this step by step—no random JAR hunting required, we’ll use proper build tools to handle dependencies, and I’ll show you exactly how to set up the connection and upload files.
First, ditch the manual JAR searches. Use Maven or Gradle to pull in all the necessary Firebase libraries automatically.
For Maven (add to your pom.xml):
<dependencies> <!-- Firebase Storage --> <dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-storage</artifactId> <version>20.3.0</version> </dependency> <!-- Firebase Admin SDK (required for server-side Java apps) --> <dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>9.2.0</version> </dependency> </dependencies>
For Gradle (add to your build.gradle):
dependencies { implementation 'com.google.firebase:firebase-storage:20.3.0' implementation 'com.google.firebase:firebase-admin:9.2.0' }
You need this JSON file to authenticate your app with Firebase:
- Go to your Firebase Console, open your project
- Click the gear icon > Project Settings > Service Accounts tab
- Click Generate New Private Key, confirm, and save the file (name it
serviceAccountKey.json) in your project'ssrc/main/resourcesfolder.
Before you can use Storage, you need to initialize the Firebase App with your service account credentials. Here’s a reusable initialization method:
import com.google.auth.oauth2.GoogleCredentials; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.cloud.StorageClient; import java.io.FileInputStream; import java.io.IOException; public class FirebaseStorageManager { private static FirebaseApp firebaseApp; public static void initializeFirebase() throws IOException { if (firebaseApp == null) { FileInputStream serviceAccount = new FileInputStream("src/main/resources/serviceAccountKey.json"); FirebaseOptions options = FirebaseOptions.builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .setStorageBucket("your-project-id.appspot.com") // Replace with your bucket name .build(); firebaseApp = FirebaseApp.initializeApp(options); } } }
Note: Replace your-project-id.appspot.com with your actual Firebase Storage bucket name—you can find this in the Firebase Console under Storage > Get Started.
Now that everything’s set up, here’s how to upload a local file or an input stream:
Upload a Local File
import com.google.cloud.storage.BlobId; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.Storage; import java.io.File; import java.io.IOException; public class FileUploader { public static void uploadLocalFile(String localFilePath, String storageFilePath) throws IOException { FirebaseStorageManager.initializeFirebase(); Storage storage = StorageClient.getInstance().bucket().getStorage(); BlobId blobId = BlobId.of("your-project-id.appspot.com", storageFilePath); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build(); // Upload the file storage.create(blobInfo, new File(localFilePath).toPath()); System.out.println("File uploaded successfully to: " + storageFilePath); } // Example usage public static void main(String[] args) throws IOException { uploadLocalFile("path/to/your/local/file.jpg", "uploads/file.jpg"); } }
Upload from an Input Stream (useful for in-memory data)
import com.google.cloud.storage.BlobId; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.Storage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; public class StreamUploader { public static void uploadInputStream(InputStream inputStream, String storageFilePath) throws IOException { FirebaseStorageManager.initializeFirebase(); Storage storage = StorageClient.getInstance().bucket().getStorage(); BlobId blobId = BlobId.of("your-project-id.appspot.com", storageFilePath); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build(); storage.create(blobInfo, inputStream); System.out.println("Stream data uploaded successfully to: " + storageFilePath); } // Example usage: upload a byte array public static void main(String[] args) throws IOException { byte[] data = "Hello Firebase Storage!".getBytes(); uploadInputStream(new ByteArrayInputStream(data), "uploads/test.txt"); } }
- Permission Denied Errors: Make sure your Firebase Storage rules allow uploads. For testing, you can use a temporary rule like:
Remember to tighten these rules for production!rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if true; } } } - Dependency Conflicts: If you run into issues with Google libraries, try updating the Firebase versions to the latest stable releases.
- File Path Issues: Double-check that your local file path is correct, and the storage file path doesn’t contain invalid characters.
内容的提问来源于stack exchange,提问作者RICARDO RIVERA TERRIQUEZ

