将图像从 ionic 发送到 asp.net 核心网络 api

Send image from ionic to asp.net core web api

我们希望将图像从 ionic 上传到 .net 核心网络 api。为此,我们使用文件传输插件。

至此,我们了解到图像将被转换为base64。然而,我们正在寻找的是如何将表单数据与多张图片一起发送到网络 api?

下面是离子方面的代码。

HTML代码触发select图片函数:

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

使用离子相机插件上传图片的组件文件代码:

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();
      });

  }

将图像传递到网络的组件文件代码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));
        });
      }

通过这样做我们可以在HttpContext.Request.Form.Files中获取文件,但是我们如何在webapi中的[FromBody]请求参数中获取这个文件呢?这样我就可以获取表单数据以及要上传的图像。

此外,我们尝试在网络中仅添加一个请求参数api,假设从客户端传递的 base64 将在请求参数中接收。但这也没有用,它给出了错误 'Value cannot be null'.

您可以使用 HttpClientModule

将 base64 数据发送到任何服务器 API

只需对代码进行以下更改

第 1 步:在 app.module.ts

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

include HttpClientModule in imports

第 2 步:在 page.ts

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

constructor(private httpClient: HttpClient) { }

在 page.ts

的构造函数中初始化 HttpClient
 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
    });
  }

快乐编码:-)