问题
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'.
回答1:
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
});
}
Happy Coding :-)
来源:https://stackoverflow.com/questions/58429122/send-image-from-ionic-to-asp-net-core-web-api