uploadFileByShareToken method
Uploads a file from localPath
using a shareToken
.
Implementation
@override
Future<String> uploadFileByShareToken({
required String localPath,
required String shareToken,
Map<String, dynamic>? metadata,
}) {
return _executeRequest(
() async {
final accessToken = await _getAccessToken();
// 1. Resolve the share URL to get the file's stable driveId and itemId.
final resolvedInfo = await _resolveShareUrlForUpload(shareToken);
if (resolvedInfo == null) {
throw Exception(
'Could not resolve the provided sharing URL for upload.');
}
// 2. Construct the Graph API URL to overwrite the file's content using its resolved IDs.
final uploadUri = Uri.parse(
'https://graph.microsoft.com/v1.0/drives/${resolvedInfo.driveId}/items/${resolvedInfo.itemId}/content');
final fileBytes = await File(localPath).readAsBytes();
// 3. Perform a PUT request with the file bytes to replace the content.
final uploadResponse = await http.put(
uploadUri,
headers: {
'Authorization': 'Bearer $accessToken',
'Content-Type':
'application/octet-stream', // Generic byte stream type.
},
body: fileBytes,
);
// A 200 or 201 status indicates a successful upload.
if (uploadResponse.statusCode >= 200 &&
uploadResponse.statusCode < 300) {
debugPrint('Successfully uploaded file to shared URL location.');
return shareToken; // Return the original token on success.
} else {
throw Exception(
'Failed to upload file content. Status: ${uploadResponse.statusCode}, Body: ${uploadResponse.body}');
}
},
operation: 'uploadToSharedUrl: $shareToken',
);
}