Cloud Storage for Firebase 可让您快速轻松地将文件上传到 Firebase 提供和管理的 Cloud Storage 存储桶中。
上传文件
如需将文件上传到 Cloud Storage,首先要创建对文件的完整路径(包括文件名)的引用。
// Create a storage reference from our appfinalstorageRef=FirebaseStorage.instance.ref();// Create a reference to "mountains.jpg"finalmountainsRef=storageRef.child("mountains.jpg");// Create a reference to 'images/mountains.jpg'finalmountainImagesRef=storageRef.child("images/mountains.jpg");// While the file names are the same, the references point to different filesassert(mountainsRef.name==mountainImagesRef.name);assert(mountainsRef.fullPath!=mountainImagesRef.fullPath);
finaltask=mountainsRef.putFile(largeFile);// Pause the upload.boolpaused=awaittask.pause();print('paused, $paused');// Resume the upload.boolresumed=awaittask.resume();print('resumed, $resumed');// Cancel the upload.boolcanceled=awaittask.cancel();print('canceled, $canceled');
finalappDocDir=awaitgetApplicationDocumentsDirectory();finalfilePath="${appDocDir.absolute}/path/to/mountains.jpg";finalfile=File(filePath);// Create the file metadatafinalmetadata=SettableMetadata(contentType:"image/jpeg");// Create a reference to the Firebase Storage bucketfinalstorageRef=FirebaseStorage.instance.ref();// Upload file and metadata to the path 'images/mountains.jpg'finaluploadTask=storageRef.child("images/path/to/mountains.jpg").putFile(file,metadata);// Listen for state changes, errors, and completion of the upload.uploadTask.snapshotEvents.listen((TaskSnapshottaskSnapshot){switch(taskSnapshot.state){caseTaskState.running:finalprogress=100.0*(taskSnapshot.bytesTransferred/taskSnapshot.totalBytes);print("Upload is $progress% complete.");break;caseTaskState.paused:print("Upload is paused.");break;caseTaskState.canceled:print("Upload was canceled");break;caseTaskState.error:// Handle unsuccessful uploadsbreak;caseTaskState.success:// Handle successful uploads on complete// ...break;}});
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-09-04。"],[],[],null,["\u003cbr /\u003e\n\nCloud Storage for Firebase allows you to quickly and easily upload files to a\n[Cloud Storage](//cloud.google.com/storage) bucket provided\nand managed by Firebase.\n| **Note:** By default, a Cloud Storage for Firebase bucket requires Firebase Authentication to perform any action on the bucket's data or files. You can change your Firebase Security Rules for Cloud Storage to [allow unauthenticated access for specific situations](/docs/storage/security/rules-conditions#public). However, for most situations, we strongly recommend [restricting access and setting up robust security rules](/docs/storage/security/get-started) (especially for production apps). Note that if you use Google App Engine and have a default Cloud Storage bucket with a name format of `*.appspot.com`, you may need to consider [how your security rules impact access to App Engine files](/docs/storage/gcp-integration#security-rules-and-app-engine-files).\n| **Note:** For Spark plan projects, Firebase blocks upload and hosting of certain executable file types for Windows (files with `.exe`, `.dll` and `.bat` extensions), Android (`.apk` extension) and Apple (`.ipa` extension) by Cloud Storage for Firebase and Firebase Hosting. This policy exists to prevent abuse on our platform. Projects on the Blaze plan are not affected. For more information, see [this FAQ](/support/faq#storage-exe-restrictions).\n\nUpload Files\n\nTo upload a file to Cloud Storage, you first create a reference to the\nfull path of the file, including the file name. \n\n // Create a storage reference from our app\n final storageRef = FirebaseStorage.instance.ref();\n\n // Create a reference to \"mountains.jpg\"\n final mountainsRef = storageRef.child(\"mountains.jpg\");\n\n // Create a reference to 'images/mountains.jpg'\n final mountainImagesRef = storageRef.child(\"images/mountains.jpg\");\n\n // While the file names are the same, the references point to different files\n assert(mountainsRef.name == mountainImagesRef.name);\n assert(mountainsRef.fullPath != mountainImagesRef.fullPath);\n\nOnce you've created an appropriate reference, you then call the\n`putFile()`, `putString()`, or `putData()` method to upload the file\nto Cloud Storage.\n\nYou cannot upload data with a reference to the root of your\nCloud Storage bucket. Your reference must point to a child URL.\n\nUpload from a file\n\nTo upload a file, you must first get the absolute path to its on-device\nlocation. For example, if a file exists within the application's documents\ndirectory, use the official [`path_provider`](https://pub.dev/packages/path_provider)\npackage to generate a file path and pass it to `putFile()`: \n\n Directory appDocDir = await getApplicationDocumentsDirectory();\n String filePath = '${appDocDir.absolute}/file-to-upload.png';\n File file = File(filePath);\n\n try {\n await mountainsRef.putFile(file);\n } on firebase_core.FirebaseException catch (e) {\n // ...\n }\n\nUpload from a String\n\nYou can upload data as a raw, `base64`, `base64url`, or `data_url` encoded\nstring using the `putString()` method. For example, to upload a text string\nencoded as a Data URL: \n\n String dataUrl = 'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==';\n\n try {\n await mountainsRef.putString(dataUrl, format: PutStringFormat.dataUrl);\n } on FirebaseException catch (e) {\n // ...\n }\n\nUploading raw data\n\nYou can upload lower-level typed data in the form of a [`Uint8List`](https://api.dart.dev/stable/2.9.2/dart-typed_data/Uint8List-class.html)\nfor those cases where uploading a string or `File` is not practical. In this\ncase, call the `putData()` method with your data: \n\n try {\n // Upload raw data.\n await mountainsRef.putData(data);\n } on firebase_core.FirebaseException catch (e) {\n // ...\n }\n\nGet a download URL\n\nAfter uploading a file, you can get a URL to download the file by calling\nthe `getDownloadUrl()` method on the `Reference`: \n\n await mountainsRef.getDownloadURL();\n\nAdd File Metadata\n\nYou can also include metadata when you upload files.\nThis metadata contains typical file metadata properties such as `contentType`\n(commonly referred to as MIME type). The `putFile()` method\nautomatically infers the MIME type from the `File` extension, but you can\noverride the auto-detected type by specifying `contentType` in the metadata. If\nyou do not provide a `contentType` and Cloud Storage cannot infer a\ndefault from the file extension, Cloud Storage uses\n`application/octet-stream`. See [Use File Metadata](/docs/storage/flutter/file-metadata). \n\n try {\n await mountainsRef.putFile(file, SettableMetadata(\n contentType: \"image/jpeg\",\n ));\n } on firebase_core.FirebaseException catch (e) {\n // ...\n }\n\nManage Uploads\n\nIn addition to starting uploads, you can pause, resume, and cancel uploads using\nthe `pause()`, `resume()`, and `cancel()` methods. Pause and resume events\nraise `pause` and `progress` state changes respectively. Canceling an\nupload causes the upload to fail with an error indicating that the\nupload was canceled. \n\n final task = mountainsRef.putFile(largeFile);\n\n // Pause the upload.\n bool paused = await task.pause();\n print('paused, $paused');\n\n // Resume the upload.\n bool resumed = await task.resume();\n print('resumed, $resumed');\n\n // Cancel the upload.\n bool canceled = await task.cancel();\n print('canceled, $canceled');\n\nMonitor Upload Progress\n\nYou can listen to a task's event stream to handle success, failure, progress, or pauses in your\nupload task:\n\n| Event Type | Typical Usage |\n|----------------------|---------------------------------------------------------------------------------------------------------------------------------|\n| `TaskState.running` | Emitted periodically as data is transferred and can be used to populate an upload/download indicator. |\n| `TaskState.paused` | Emitted any time the task is paused. |\n| `TaskState.success` | Emitted when the task has successfully completed. |\n| `TaskState.canceled` | Emitted any time the task is canceled. |\n| `TaskState.error` | Emitted when the upload has failed. This can happen due to network timeouts, authorization failures, or if you cancel the task. |\n\n mountainsRef.putFile(file).snapshotEvents.listen((taskSnapshot) {\n switch (taskSnapshot.state) {\n case TaskState.running:\n // ...\n break;\n case TaskState.paused:\n // ...\n break;\n case TaskState.success:\n // ...\n break;\n case TaskState.canceled:\n // ...\n break;\n case TaskState.error:\n // ...\n break;\n }\n });\n\nError Handling\n\nThere are a number of reasons why errors may occur on upload, including\nthe local file not existing, or the user not having permission to upload\nthe desired file. You can find more information about errors in the\n[Handle Errors](/docs/storage/flutter/handle-errors) section of the docs.\n\nFull Example\n\nA full example of an upload with progress monitoring and error handling\nis shown below: \n\n final appDocDir = await getApplicationDocumentsDirectory();\n final filePath = \"${appDocDir.absolute}/path/to/mountains.jpg\";\n final file = File(filePath);\n\n // Create the file metadata\n final metadata = SettableMetadata(contentType: \"image/jpeg\");\n\n // Create a reference to the Firebase Storage bucket\n final storageRef = FirebaseStorage.instance.ref();\n\n // Upload file and metadata to the path 'images/mountains.jpg'\n final uploadTask = storageRef\n .child(\"images/path/to/mountains.jpg\")\n .putFile(file, metadata);\n\n // Listen for state changes, errors, and completion of the upload.\n uploadTask.snapshotEvents.listen((TaskSnapshot taskSnapshot) {\n switch (taskSnapshot.state) {\n case TaskState.running:\n final progress =\n 100.0 * (taskSnapshot.bytesTransferred / taskSnapshot.totalBytes);\n print(\"Upload is $progress% complete.\");\n break;\n case TaskState.paused:\n print(\"Upload is paused.\");\n break;\n case TaskState.canceled:\n print(\"Upload was canceled\");\n break;\n case TaskState.error:\n // Handle unsuccessful uploads\n break;\n case TaskState.success:\n // Handle successful uploads on complete\n // ...\n break;\n }\n });\n\nNow that you've uploaded files, let's learn how to [download them](/docs/storage/flutter/download-files)\nfrom Cloud Storage."]]