upload method
Uploads a file or content to a storage bucket.
This method supports uploading content from various sources including byte arrays, strings, or file paths. The uploaded file will be stored in the specified bucket with the given key and metadata.
Parameters
content: The file content as bytes or string (optional if filePath provided)filePath: Path to the file to upload (optional if content provided)contentType: MIME type of the contentbucket: Name of the target bucket (required)key: Unique key/path for the file within the bucket (required)description: Optional description of the filetags: Optional list of tags for organizationsha256: Optional SHA256 hash for integrity verificationtype: Optional custom type classification
Returns
A Future that resolves to a BucketFile representing the uploaded file
Throws
- Exception if neither content nor filePath is provided
HttpExceptionif there's a network errorCalljmpExceptionif the upload fails or bucket doesn't exist
Examples
// Upload image from bytes
final imageFile = await calljmp.storage.upload(
content: imageBytes,
contentType: MediaType('image', 'png'),
bucket: 'images',
key: 'gallery/photo1.png',
description: 'Holiday photo',
tags: ['vacation', '2023'],
);
// Upload document from file path
final document = await calljmp.storage.upload(
filePath: '/path/to/report.pdf',
bucket: 'documents',
key: 'reports/monthly-report.pdf',
tags: ['report', 'monthly'],
);
// Upload text content
final textFile = await calljmp.storage.upload(
content: 'Hello, world!',
contentType: MediaType('text', 'plain'),
bucket: 'text-files',
key: 'messages/hello.txt',
);
Implementation
Future<BucketFile> upload({
dynamic content,
String? filePath,
MediaType? contentType,
required String bucket,
required String key,
String? description,
List<String>? tags,
String? sha256,
String? type,
}) async {
final formData = http.FormData();
formData.addField(
"metadata",
jsonEncode({
'sha256': sha256,
'type': type,
'description': description,
'tags': tags,
}),
);
if (content is String) {
formData.addFile(
http.MultipartFile.fromString(
'content',
content,
contentType: contentType,
),
);
} else if (content is List<int>) {
formData.addFile(
http.MultipartFile.fromBytes(
'content',
content,
contentType: contentType,
),
);
} else if (filePath != null) {
formData.addFile(
await http.MultipartFile.fromPath(
'content',
filePath,
contentType: contentType,
),
);
} else {
throw ArgumentError(
'Content must be a String or List<int>, or filePath must be provided',
);
}
return http
.request('${_config.serviceUrl}/data/$bucket/$key')
.use(http.context(_config))
.use(http.access())
.post(formData)
.json((json) => BucketFile.fromJson(json));
}