2017-10-19 325 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

祝你好運!