2017-10-19 78 views
0

我试图将Blob文件上传到Firebase,但我一直收到“undefined”作为“makeFileIntoBlob”函数的返回。我在Android上运行它。 我可以在拍照后获取文件路径,但是当我调用该函数来检索Blob并将其上传到Firebase时,我将Blob文件设置为“未定义”。 一些帮助?将文件转换为TypeScript上的Blob for Ionic

继承人,我把图片上传到火力地堡存储

uploadToFirebase(imageBlob) { 
var fileName = 'sample.jpg'; 
return new Promise((resolve, reject) => { 
var fileRef = firebase.storage().ref('Animais/' + fileName); 

var uploadTask = fileRef.put(imageBlob); 

uploadTask.on('state_changed', (snapshot) => { 
    console.log('snapshot progess ' + snapshot); 
}, (_error) => { 
    reject(_error); 
},() => { 
    // completion... 
    resolve(uploadTask.snapshot); 
}); 
}); 
} 

继承人的功能,我尝试从文件路径

makeFileIntoBlob(imagePath) { 

var reader = new FileReader(); 
reader.onloadend = (evt: any) => { 
    var imgBlob: any = new Blob(imagePath); 
    imgBlob.name = 'sample.jpg'; 
    return imgBlob; 
}; 
reader.onerror = (e) => { 
    console.log('Failed file read: ' + e.toString()); 
}; 

继承人在那里我拍照

的功能做一个斑点的功能
takePic(){ 

let imageSource; 

this.camera.getPicture({ 
    destinationType: this.camera.DestinationType.FILE_URI, 
    sourceType: imageSource, 
    encodingType: this.camera.EncodingType.JPEG, 
    targetHeight: 640, 
    correctOrientation: true, 
    saveToPhotoAlbum : true 
}).then((imagePath) => { 
    alert('got image path ' + imagePath); 
    // convert picture to blob 
    return this.makeFileIntoBlob(imagePath); 
}).then((imageBlob) => { 
    alert('got image blob ' + imageBlob); 
    // upload the blob 
    return this.uploadToFirebase(imageBlob); 
}).then((uploadSnapshot: any) => { 
    alert('file uploaded successfully ' + uploadSnapshot.downloadURL); 
    // store reference to storage in database 
    return this.saveToDatabaseAssetList(uploadSnapshot); 
}).then((uploadSnapshot: any) => { 
    //alert('file saved to asset catalog successfully '); 
}, (error) => { 
    alert('Error ' + (error.message || error)); 
}); 
+0

你真的在使用TypeScript吗?你得到什么编译器错误?什么是BLOB? – jcalz

+0

是的,Typescript,Ionic3。抱歉,BLOB,只是我正在尝试的调试,已经编辑它。我没有收到编译器错误,我只是将“undefined”作为函数“makeFileIntoBlob”的返回值。 –

+0

这可能是[的Javascript少辉用的FileReader()](https://stackoverflow.com/questions/34495796/javascript-promises-with-filereader),因为你的问题是,你使用的是'FileReader'但重复不使用其回调来解决/拒绝“承诺”。 – jcalz

回答

0

正如我在评论中所说,你的问题是你正在使用FileReader,但不使用其回调来解决/拒绝Promise。您需要返回Promise。您实际上并未使用FileReader来读取imagePath中的任何内容,但我甚至不知道这是否会起作用,因为FileReader读取的是File s或Blob s,而不是URI。如果URI是data:// URI,则可以使用一些代码将其转换为Blob。如果这是一个file:// URI,那么除非您是chrome-privileged,否则您无权在浏览器中执行此操作。等等,你在浏览器中吗?我想你posted enough info for anyone to reproduce。你在使用Cordova吗?如果是这样,为什么不使用返回的file:// url与File Transfer API而不是试图通过它FileReader?如果这不起作用,我不能真正帮助你,因为我对科尔多瓦一无所知。您可能需要添加标签,以便其他人可以帮助您。并且一定要搜索StackOverflow其他可能适用的relevant questions

祝你好运!