将图片上传到 Firebase 存储时出错



我正在使用Ionic制作一个应用程序,我希望用户选择图像,裁剪并上传。为此,我正在使用科尔多瓦相机插件和科尔多瓦裁剪插件。这是我的文件选择器代码:

OpenFilePicker() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: 0  //0 = Chose File; 1 = Take picture
}
this.camera.getPicture(options).then((imageData) => {
//Using the crop plugin:
this.crop.crop(imageData, {quality: 75})
.then((newPath) => {
//Creating the blob
this.blobimg = new Blob([newPath], {type : 'image/jpeg'});
})
.catch((err) => {
// Handle error crop plugin
})
}, (err) => {
// Handle error camera plugin
});
} 

然后我将创建的 blob 上传到 firebase 存储:

[...]
const imageRef = storageRef.child(`profilePics/photo.jpg`).put(this.blobimg);

它说它很成功,但上传的图像只有 105 B,并且全黑(也就是说,它不是真正的图像(。

我在这里做错了什么?

我遇到了完全相同的问题,因此 blob 可能未完全创建或不完整 - 我仍在研究它,所以一旦我找到解决方案,就会回复您

好的,我已经破解了它!,您需要使用 canvas 将图像转换为 base64,然后将其作为data_url上传到 Firebase,代码如下,用 vuejs 编写,但我相信你可以重构。

photoUpload: function () {
var img = new Image()
var c = document.createElement('canvas')
var ctx = c.getContext('2d')
let storage = firebase.storage()
let storageRef = storage.ref()
let filesRef = storageRef.child('images/' + this.photo)
// window.alert(img.src)
img.onload = function () {
c.width = this.naturalWidth     // update canvas size to match image
c.height = this.naturalHeight
ctx.drawImage(this, 0, 0)
var dataURL = c.toDataURL('image/jpeg', 0.75)
filesRef.putString(dataURL, 'data_url')
.then((snapshot) => {
window.alert('Uploaded a blob or file!')
var downloadURL = snapshot.downloadURL
window.alert(downloadURL)
}).catch((error) => {
window.alert(error)
})
}
img.crossOrigin = ''             // if from different origin
img.src = this.photoURL
},

最新更新