此代码成功上传了文件,但下载后不会显示下载网址
控制台显示错误
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<script>
var config = {
// Initialize Firebase
};
firebase.initializeApp(config);
var snapshot;
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change' , function(e) {
var file= e.target.files[0];
var storageRef = firebase.storage().ref('pics/' + file.name);
var task = storageRef.put(file);
task.on('state_changed' ,
function progress(){
var percentage = (task.snapshot.bytesTransferred / task.snapshot.totalBytes) * 100;
uploader.value = percentage;
},
function error(err){
},
function complete(res)
{
console.log("Complete Response :" + res);
}
);
});
snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log("File available at", downloadURL);
});
</script>
*我希望在文件上传后立即打印下载链接*
答案 0 :(得分:0)
您需要在附近的代码中稍作修改。
function progress(){
var percentage = (task.snapshot.bytesTransferred / task.snapshot.totalBytes) * 100;
uploader.value = percentage;
},
function error(err){
},
function complete(res)
{
console.log("Complete Response :" + res);
}
,function(){
snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log("File available at", downloadURL);
});
}
参考Firebase:
// File or Blob named mountains.jpg
var file = ...
// Create the file metadata
var metadata = {
contentType: 'image/jpeg'
};
// Upload file and metadata to the object 'images/mountains.jpg'
var uploadTask = storageRef.child('images/' + file.name).put(file, metadata);
// Listen for state changes, errors, and completion of the upload.
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;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
...
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
}, function() {
// Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});