Xamarin.Forms ファイルをMultipartでPostする

  1. Google App Engine Java Standard + Spring Boot 環境構築
  2. Spring Bootのテンプレートエンジン Thymeleafを適用

  3. Spring BootにVue.jsを利用する

  4. Spring BootにVuetify導入からクロスドメインAjax通信

  5. Spring Boot+Vuetify GAEへデプロイ、動作確認

  6. Xamarin.FormsアプリをiOS用にビルド

  7. Xamarin.Forms ポップアップの表示と Http通信

  8. Spring Boot+Vuetify ファイルのアップロードとJSONで結果を返す

  9. Google Google Cloud Vision でOCR。VuetifyからSpringBoot経由で呼び出し

  10. Xamarin ファイル選択

1.ファイルのアップロード

GAE側で、Google Cloud Vision APIを使って、OCRを実行するAPIを作成 し、Xamarinでファイルを選択することが出来たので、APIに、Multipart Postでファイルを送信し、OCRの結果を得る。

https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadfile?

https://stackoverflow.com/questions/19954287/how-to-upload-file-to-server-with-http-post-multipart-form-data

この辺りを参考に。

  1. private async void FilePick()
  2. {
  3. var file = await CrossFilePicker.Current.PickFile();
  4.  
  5. if (file != null)
  6. {
  7. byte[] fileBytes = null;
  8. using(MemoryStream ms = new MemoryStream()) {
  9. byte[] buf = new byte[1024 * 16];
  10. int read;
  11. var inputStream = file.GetStream();
  12. while ((read = inputStream.Read(buf,0,buf.Length)) > 0)
  13. {
  14. ms.Write(buf, 0, read);
  15. }
  16.  
  17. fileBytes = ms.ToArray();
  18. }
  19. if (fileBytes != null)
  20. {
  21. string uri = "https://favophrase.com/api/upload-file";
  22.  
  23. HttpClient httpClient = new HttpClient();
  24. MultipartFormDataContent form = new MultipartFormDataContent();
  25.  
  26. form.Add(new StringContent(file.FileName), "fileName");
  27.  
  28. form.Add(new ByteArrayContent(fileBytes, 0, fileBytes.Length), "file", file.FilePath);
  29. HttpResponseMessage response = await httpClient.PostAsync(uri, form);
  30.  
  31. response.EnsureSuccessStatusCode();
  32. httpClient.Dispose();
  33.  
  34. string sd = response.Content.ReadAsStringAsync().Result;
  35.  
  36. await Page.DisplayAlert("Uploaded File.", sd, "OK");
  37. }
  38. }
  39. }

2.実行結果

Android,iPhone,UWP にて、それぞれ、ファイル選択から、ファイルアップロード、OCRの結果を表示できた。

xamarin_fileupload_android


xamarin_fileupload_ios

xamarin_fileupload_uwp

いい感じ。

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です