我有一个离子3应用程序;我正在处理上传 Profiles 图片功能 . 在这里,我想使用相机从图库或捕获图像中选择图像 . 之后,我将有两个images / image_paths . 我想上传这两个图像以及user_id,access_token
选择图像从图库中选择= { Headers :'选择图片',消息:'选择最少1张图片',maximumImagesCount:1,outType:0};
this.imagePicker.getPictures(option).then(results => {
for (var i = 0; i < results.length; i++) {
// alert('Image URI: ' + results[i]);
this.imageSelected = "data:image/jpeg;base64," +results[i];
// this.imageSelected = results[i];
let option = {
quality: 100,
targetHeight: 400,
targetWidth: 400,
};
this.crop.crop(this.imageSelected, option).then((data) => {
this.imageCropped = "data:image/jpeg;base64," +data;
// alert(this.imageCropped);
this.saveProfileImage(this.imageSelected, this.imageCropped);
}, err => {
this.imageCropped = '';
alert(err);
});
}
}, err => {
this.imageSelected = '';
alert('Error' + err);
})
从相机选择一个图像让选项:CameraOptions = {quality:100,destinationType:this.camera.DestinationType.DATA_URL,encodingType:this.camera.EncodingType.JPEG,mediaType:this.camera.MediaType.PICTURE}
this.camera.getPicture(options).then((imageData) => {
// alert(imageData);
this.imageSelected = "data:image/jpeg;base64," +imageData;
let option = {
quality: 100,
targetHeight: 400,
targetWidth: 400,
};
this.crop.crop(this.imageSelected, option).then((data) => {
this.imageCropped = "data:image/jpeg;base64," +data;
this.saveProfileImage(this.imageSelected, this.imageCropped);
}, err => {
this.imageCropped = '';
alert(err);
});
}, (err) => {
this.imageSelected = '';
alert('Error' + err);
});
请参阅上面的代码,如果它是正确的,建议我如何使用表单数据或任何其他方法编写上传功能
2 回答
即使我在一段时间后面临同样的问题,也没有在网上找到适当的解决方案 . 下面是解决方案,我在一些研究后发现并且工作得非常好,不仅适用于图像,还适用于其他文件 . 既然问题是关于图像,我将解释图像的答案w.r.t . (除了选择文件之外,其他文件的过程保持不变) .
从相机中选择图像的代码:
从库中选择图像的代码:
下面是将所选图像转换为base64的代码片段,我已经为相机编写了它,它对于图库来说仍然是相同的 . 将图像转换为base64后,将其推送到数组 . 现在,您可以选择多个图像并将其值存储在数组中 .
现在通过API将数据发送到服务器 . 您可以使用cordova-plugin-advanced-http或Angular-http来实现它 . API应该采用数组格式的图像以及其他参数 . 由于base64图像将是一个长度更大的字符串,因此建议使用url编码格式的formData或row,以用于REST的post方法 .
现在在后端,将解析正文并提取图像数组 . 在用于编写API的所有流行的后端语言(Java,PHP,NodeJS,C#等)中,有一些免费库可以将base64图像转换为实际图像 .
Whola,就是这样,现在您可以通过API将多个图像发送到您的服务器 . 除了图像,如果您尝试选择任何其他MIME类型的文件(pdf,doc,docx等),您可以使用相同的方法 .
我还在以下位置创建了一个git hub存储库:https://github.com/coolvasanth/upload-multiple-image-files-in-Ionic-3-4/blob/master/README.md
首先,您需要创建一个
formData object
.Need to change imagePicker
Need to change in camera
Setup POST method
First of all you need to inject HttpClientModule in import section of app.module.ts file
Then inject private http: HttpClient inside constructor in saveProfileImage() funtion class
change in saveProfileImage()