[英]file upload to firebase storage is not working (“storage/invalid-argument”)
我正在嘗試在上載時顯示圖像,然后將該圖像添加到Firebase。 我能夠顯示圖像,但是當我嘗試上傳時,出現一條錯誤消息,提示我無法弄清楚。 這是我的代碼
html
<input type="file" accept="image/*" onchange="showMainImage(this)" />
<br/>
<img id="thumbnil" style="width:40%; margin-top:10px;" src="" alt="image"/>
JS
function showMainImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img=document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var BusinessesId = firebase.auth().currentUser.uid;
//Get file
var filename = files.name;
//Create storage reference
var storageRef = firebase.storage().ref("ProductImages/"+BusinessesId+"/"+filename);
//Upload file
var task = storageRef.put(files).then(function(snapshot) {
console.log('Uploaded', snapshot.totalBytes, 'bytes.');
var url = snapshot.downloadURL;
// productImageUrl.value = url;
console.log('File available at', url);
// [START_EXCLUDE]
}).catch(function(error) {
// [START onfailure]
console.error('Upload failed:', error);
// [END onfailure]
});
// [END oncomplete]
}
})
}
我從控制台獲得
{t:“存儲/無效參數”,e:“ Firebase存儲:索引0處
put
了無效參數:預期的Blob或文件。”,n:null,r:“ FirebaseError”}代碼:(...)e :“ Firebase存儲:索引0處put
了無效參數:預期的Blob或文件。”
從錯誤消息中我認為文件的格式不正確。 如何解決此錯誤並上傳文件?
put方法將非空Blob,非空Uint8Array或非空ArrayBuffer作為第一個參數。 https://firebase.google.com/docs/reference/js/firebase.storage.Reference#put
考慮切換到putString方法,因此您可以將任何String設置為所需的任何格式。 https://firebase.google.com/docs/reference/js/firebase.storage.Reference#putString
您應該先轉換對象。
這是我的實現:我還使用了STATE_CHANGED來監視圖片的上傳百分比:
self.uploadPicture = function() {
var userId = self.user().uid;
var storageRef = firebase.storage().ref().child('images/'+userId);
var data = self.fileData().dataURL();
var uploadTask = storageRef.putString(data, 'data_url');
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function(snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
self.percentage(Math.round(progress));
}, function(error) {
toastr.error(error.code,error.message);
}, function() {
toastr.success("Immagine profilo Aggiornata");
self.savedPicture(true);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.