顯示具有 Angilar 標籤的文章。 顯示所有文章
顯示具有 Angilar 標籤的文章。 顯示所有文章

2021年9月29日 星期三

[Q&A] Send image from ionic to asp.net core (IFormFile) web api

 [Q]

We are looking to upload image from ionic to .net core web api. To achieve this we are using file transfer plugin.

So, far we understood that image will be converted into base64. However, what we are looking is how can we sent form data along with multiple image to web api?

Below is the code from ionic side.

HTML code to trigger select image function:

<ion-button fill="clear" expand="full" color="light" (click)="selectImage()">
      <ion-icon slot="start" name="camera"></ion-icon>
      Select Image</ion-button>

Component file code to upload image using ionic camera Plugin:

async selectImage() {
      const actionSheet = await this.actionSheetController.create({
          header: "Select Image source",
          buttons: [{
                  text: 'Load from Library',
                  handler: () => {
                      this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
                  }
              },
              {
                  text: 'Use Camera',
                  handler: () => {
                      this.takePicture(this.camera.PictureSourceType.CAMERA);
                  }
              },
              {
                  text: 'Cancel',
                  role: 'cancel'
              }
          ]
      });
      await actionSheet.present();
  }

  takePicture(sourceType: PictureSourceType) {
      var options: CameraOptions = {
          quality: 100,
          sourceType: sourceType,
          saveToPhotoAlbum: false,
          correctOrientation: true
      };

      this.camera.getPicture(options).then(imagePath => {
        this.base64img="data:image/jpeg;base64,"+imagePath;
        this.uploadPic();
      });

  }

Component file code to pass image to web api:

uploadPic() {
        const fileTransfer: FileTransferObject = this.transfer.create();
        let filename = this.base64img.split('/').pop();
        let options: FileUploadOptions = {
            fileKey: "file",
            fileName: filename,
            chunkedMode: false,
            mimeType: "image/jpg",
            params: { 'title': this.imageTitle }
        }

        fileTransfer.upload(this.base64img, '<api endpoint>', options).then(data => {
          alert(JSON.stringify(data));
        }, error => {

          alert("error");
          alert("error" + JSON.stringify(error));
        });
      }

By doing this we are able to get the file in HttpContext.Request.Form.Files, but how can we get this in [FromBody] request parameter in web api? So, that I can get form data as well images to upload.

Also, we have tried by adding only one request parameter in web api, by assuming that the base64 which passed from client side will be received at in request parameter. But this also didn't work, which has given error 'Value cannot be null'.




[A]


You can send base64 data to any server API using HttpClientModule

Just do following changes in your code

Step 1: In app.module.ts

import { HttpClientModule } from '@angular/common/http';

include HttpClientModule in imports

Step 2: In page.ts

import { HttpClient } from '@angular/common/http';

constructor(private httpClient: HttpClient) { }

Initialise HttpClient in the constructor of page.ts

 sendData(base64img,other_data) {
    let _url = "";
    let formData = new FormData();
    formData.append("base64img", base64img);
    formData.append("other_data", other_data);
    this.httpClient.post(_url, formData).subscribe((res) => {
    //res contains server response
    });
  }





from:
https://stackoverflow.com/questions/58429122/send-image-from-ionic-to-asp-net-core-web-api

2021年3月24日 星期三

關於 RxJS 裡的 BehaviorSubject 可以怎麼用!

 RxJS 裡的 Subject 有 4 種類型,Subject、BehaviorSubject、ReplaySubject 和 AsyncSubject,每一種類型的 Subject 都有各自的特性及使用時機,這次會使用 BehaviorSubject來管理使用者的登入狀態


BehaviorSubject

BehaviorSubject 與一般的 Subject 有什麼不一樣,差別有兩個

  1. BehaviorSubject 可以給予初始值
  2. 每一個 Observer 都可以在註冊的當下,立刻取得目前 BehavoirSubject 的值 (以下皆簡稱為 Subject)

這兩種特性,就非常適合用在使用者登入狀態管理的這種情境

使用情境

使用者登入基本上,狀態就兩種,登入與尚未登入,而每一個頁面都可以在取得該使用者目前的登入狀態。也可以即時知道已登入的使用者登出的時間點。

根據上列的描述,我們會實作一個 UserService,用來執行跟管理使用者的登入,登出行為及狀態。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from "rxjs";

@Injectable()
export class UserService {
isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());

/**
* 如果有取得token,表示使用者有登入系統
* @returns {boolean}
*/
private hasToken() : boolean {
return !!localStorage.getItem('token');
}

/**
* 登入使用者,並通知所有訂閱者
*/
login() : void {
localStorage.setItem('token', 'JWT');
this.isLoginSubject.next(true);
}

/**
* 登出使用者,並通知所有訂閱者
*/
logout() : void {
localStorage.removeItem('token');
this.isLoginSubject.next(false);
}

/**
*
* @returns {Observable<T>}
*/
isLoggedIn() : Observable<boolean> {
return this.isLoginSubject.asObservable();
}
}

Component 的使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { Component, OnInit } from '@angular/core';
import { AuthService } from "../auth.service";
import { Observable } from "rxjs";

@Component({
selector: 'app-main-nav',
template: `
<ul>
<li *ngIf="!(isLoggedIn | async)" (click)="authService.login()>
<a>Login</a>
</li>
<li *ngIf="(isLoggedIn | async)" (click)="authService.logout()">
<a>Logout</a>
</li>
</ul>
`
})
export class MainNavComponent implements OnInit {
isLoggedIn : Observable<boolean>;

constructor( public userService : UserService ) {
this.isLoggedIn = userService.isLoggedIn();
}
}

這樣子就完成了一個陽春型的使用者登入狀態管理 service。



參考資料

[Q&A] Send image from ionic to asp.net core (IFormFile) web api

 [Q] We are looking to upload image from ionic to .net core web api. To achieve this we are using file transfer plugin. So, far we understoo...