@@ -499,7 +499,7 @@ public async Task<string> TransferOwnership(string model, string emailAddress)
499
499
/// Uploads a file to the File API backend.
500
500
/// </summary>
501
501
/// <param name="uri">URI or path to the file to upload.</param>
502
- /// <param name="displayName">A name displazed for the uploaded file.</param>
502
+ /// <param name="displayName">A name displayed for the uploaded file.</param>
503
503
/// <param name="resumable">Flag indicating whether to use resumable upload.</param>
504
504
/// <param name="cancellationToken">A cancellation token to cancel the upload.</param>
505
505
/// <returns>A URI of the uploaded file.</returns>
@@ -557,6 +557,53 @@ public async Task<UploadMediaResponse> UploadFile(string uri,
557
557
}
558
558
}
559
559
560
+ public async Task < UploadMediaResponse > UploadFile ( Stream stream ,
561
+ string displayName ,
562
+ string mimeType ,
563
+ bool resumable = false ,
564
+ CancellationToken cancellationToken = default )
565
+ {
566
+ if ( stream == null ) throw new ArgumentNullException ( nameof ( stream ) ) ;
567
+ if ( stream . Length > Constants . MaxUploadFileSize ) throw new MaxUploadFileSizeException ( nameof ( stream ) ) ;
568
+ if ( string . IsNullOrEmpty ( mimeType ) ) throw new ArgumentException ( nameof ( mimeType ) ) ;
569
+ if ( string . IsNullOrEmpty ( displayName ) ) throw new ArgumentException ( nameof ( displayName ) ) ;
570
+
571
+ var totalBytes = stream . Length ;
572
+ var request = new UploadMediaRequest ( )
573
+ {
574
+ File = new FileRequest ( )
575
+ {
576
+ DisplayName = displayName
577
+ }
578
+ } ;
579
+
580
+ var url = $ "{ EndpointGoogleAi } /upload/{ Version } /files"; // v1beta3 // ?key={apiKey}
581
+ if ( resumable )
582
+ {
583
+ url = $ "{ EndpointGoogleAi } /resumable/upload/{ Version } /files"; // v1beta3 // ?key={apiKey}
584
+ }
585
+ url = ParseUrl ( url ) . AddQueryString ( new Dictionary < string , string ? > ( )
586
+ {
587
+ [ "alt" ] = "json" ,
588
+ [ "uploadType" ] = "multipart"
589
+ } ) ;
590
+ string json = Serialize ( request ) ;
591
+
592
+ var multipartContent = new MultipartContent ( "related" ) ;
593
+ multipartContent . Add ( new StringContent ( json , Encoding . UTF8 , Constants . MediaType ) ) ;
594
+ multipartContent . Add ( new StreamContent ( stream , ( int ) Constants . ChunkSize )
595
+ {
596
+ Headers = {
597
+ ContentType = new MediaTypeHeaderValue ( mimeType ) ,
598
+ ContentLength = totalBytes
599
+ }
600
+ } ) ;
601
+
602
+ var response = await Client . PostAsync ( url , multipartContent , cancellationToken ) ;
603
+ await response . EnsureSuccessAsync ( ) ;
604
+ return await Deserialize < UploadMediaResponse > ( response ) ;
605
+ }
606
+
560
607
/// <summary>
561
608
/// Lists the metadata for Files owned by the requesting project.
562
609
/// </summary>
0 commit comments