我尝试在上传时显示图像,然后将该图像添加到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:&#34; storage / invalid-argument&#34;,e:&#34; Firebase存储:
put
中索引0处的无效参数:预期的Blob或文件。&#34;, n:null,r:&#34; FirebaseError&#34;} 码 : (......) Ë : &#34; Firebase存储:索引0处的put
中的参数无效:预期的Blob或文件。&#34;
从错误消息我认为文件没有正确格式化。如何修复此错误并上传文件?
答案 0 :(得分:0)
方法put将第一个参数作为非null Blob,非null Uint8Array或非null 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);
});