我正在使用Ionic4。我想将图像从API下载到手机上。该图像是base64图像。下载图像时,图像显示不支持文件格式或文件损坏。如何解决此问题?这是我的代码:
this.http.get('SERVER_URL', {...httpOptions, responseType: 'blob'})
.subscribe((data: Blob) => {
const fileName = 'img.jpg';
this.file.writeFile(this.file.externalRootDirectory + 'Pictures/', fileName, data, {replace: true})
}, errorRes => {
console.error(errorRes);
});
有人可以帮助我吗?非常感谢
答案 0 :(得分:0)
我已经用离子3做到了这一点。 它应该工作。 将getPicture替换为http请求,并将base64ImageData替换为从服务器获取的内容
public getPicture() {
let base64ImageData;
this.camera.getPicture().then((imageData) => {
//here converting a normal image data to base64 image data.
base64ImageData = 'data:image/jpeg;base64,' + imageData;
// item.img.push(imageData)
/**here passing three arguments to method
*Base64 Data
*Folder Name
*File Name
*/
const directory = "folderName"
this.writeFile(base64ImageData, imageData, directory, 'file_name.jpeg');
}, (error) => {
console.log('Error Occured: ' + error);
});
};
//here is the method is used to write a file in storage
public writeFile(base64Data: any, imageData:any, folderName: string, fileName: any) {
let contentType = this.getContentType(base64Data);
// let content
let DataBlob = this.base64toBlob(imageData, contentType);
// here iam mentioned this line this.file.externalRootDirectory is a native pre-defined file path storage. You can change a file path whatever pre-defined method.
let filePath = this.file.externalRootDirectory + folderName;
this.file.writeFile(filePath, fileName, DataBlob, contentType).then((success) => {
console.log("File Writed Successfully", success);
}).catch((err) => {
console.log("Error Occured While Writing File", err);
})
}
//here is the method is used to get content type of an bas64 data
public getContentType(base64Data: any) {
let block = base64Data.split(";");
let contentType = block[0].split(":")[1];
return contentType;
}