我正在将文件上传到Firebase存储后尝试获取下载URL,到目前为止,我已经能够上传文件,但是对于URL,我一直未定义,这是我的代码:
onFileChanged(event) {
const file: File = event.target.files[0];
const metaData = {'contentType': file.type};
const storRef: firebase.storage.Reference = firebase.storage().ref('/MyFolder/' + file.name);
const uploadTask: firebase.storage.UploadTask = storRef.put(file, metaData);
console.log('Uploading:' + file.name);
uploadTask.then((uploadSnapshot: firebase.storage.UploadTaskSnapshot) => {
const imageUrl = uploadSnapshot.downloadURL;
console.log('URL:' + imageUrl);
}); }
任何建议 谢谢
答案 0 :(得分:2)
通过替换
uploadTask.then((uploadSnapshot: firebase.storage.UploadTaskSnapshot) => {
const imageUrl = uploadSnapshot.downloadURL;
console.log('URL:' + imageUrl);
});
到
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
const imageUrl = downloadURL;
console.log('URL:' + imageUrl);
});
答案 1 :(得分:1)
UploadTaskSnapshot不再具有downloadURL属性(单击以查看API文档以自己查看)。不久前就消除了。
相反,您应该在Reference对象上使用Reference.getDownloadURL()来请求URL。
答案 2 :(得分:1)
使用“ snapshot.ref.getDownloadURL()”提供下载URL。
encodeImageUri(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function () {
var aux:any = this;
c.width = aux.width;
c.height = aux.height;
ctx.drawImage(img, 0, 0);
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
};
img.src = imageUri;
};
uploadProfileImage(imageURI, path) {
console.log("path = " + path);
console.log("imageURI = " + imageURI);
return new Promise<any>((resolve, reject) => {
let storageRef = firebase.storage().ref();
let imageRef = storageRef.child('profile').child(path);
this.encodeImageUri(imageURI, function (image64) {
imageRef.putString(image64, 'data_url')
.then(snapshot => {
console.log("snapshot = " + snapshot);
resolve(snapshot.ref.getDownloadURL())
}, err => {
reject(err);
console.log(err);
})
})
})
}
答案 3 :(得分:0)
如前所述,UploadTaskSnapshot
不再具有 downloadURL
属性。相反,您需要使用 getDownloadURL
中的方法 AngularFireStorageReference
。
以下是开始上传代码的示例:
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.scss'],
})
export class FileUploadComponent {
task: AngularFireUploadTask;
taskRef: AngularFireStorageReference;
percentage: Observable<number>;
snapshot: Observable<any>;
downloadURL: Observable<string>;
constructor(private storage: AngularFireStorage) {}
startUpload(event: FileList) {
const file = event.item(0);
if (file.type.split('/')[0] !== 'image') {
console.error('unsupported file type');
return;
}
const path = `test/${new Date().getTime()}_${file.name}`;
const customMetadata = { app: 'My App' };
this.taskRef = this.storage.ref(path);
this.task = this.taskRef.put(file, { customMetadata });
this.percentage = this.task.percentageChanges();
this.snapshot = this.task.snapshotChanges();
this.downloadURL = this.taskRef.getDownloadURL();
}
}