【发布时间】:2021-07-10 05:15:10
【问题描述】:
我让我的用户上传他们的个人资料图片,该图片显示为 150x150 像素的圆圈,我希望在他选择图片上传到 Firebase 时调整图片大小/压缩。这是我用来选择和上传图片的 JavaScript:
<label for="upload-picture" class="upload-picture button-small">Upload Picture</label>
<input id="upload-picture" type="file" style="display: none" (change)="uploadPicture($event)" accept=".jpeg,.jpg,.png,.svg">
import { Component, OnInit } from '@angular/core';
import { AngularFirestoreDocument } from '@angular/fire/firestore';
import { FbUser } from 'src/app/common/fb-user';
import { AuthService } from 'src/app/services/auth.service';
@Component({
selector: 'app-profile-info',
templateUrl: './profile-info.component.html',
styleUrls: ['./profile-info.component.scss']
})
export class ProfileInfoComponent implements OnInit {
constructor(
public _auth: AuthService,
) { }
ngOnInit(): void {
}
currentImageUrl: string = "";
async uploadPicture(e: any) {
const file = e.target.files[0]
//Here i want to reduce image size
//(image shows as a 150x150 in the DOM so i dont need it to be bigger than that since firebase has a 5GB limit of free storage)
const filePath = this._auth.userData.uid
const task = await this.uploadImage(filePath, file)
if (task) {
this.currentImageUrl = await this._auth._afstg.ref(task).getDownloadURL().toPromise();
const userRef: AngularFirestoreDocument<any> = this._auth._afs.doc(`users/${filePath}`);
const userData: FbUser = {
uid: filePath,
email: this._auth.userData.email,
displayName: this._auth.userData.displayName,
photoURL: this.currentImageUrl,
emailVerified: this._auth.userData.emailVerified
}
userRef.set(userData, {
merge: true
})
alert("Image Uploaded Successfully")
window.location.reload()
} else {
alert("Error when uploading image, try again")
}
}
async uploadImage(uid: string, file: any): Promise<string> {
const fileRef = this._auth._afstg.ref(uid).child("profile-picture");
// Upload file in reference
if (!!file) {
const result = await fileRef.put(file);
return result.ref.fullPath;
}
return ""
}
}
我尝试了很多方法,但似乎都没有奏效,有人知道或以前做过吗?
【问题讨论】:
-
你应该尝试使用这个:npmjs.com/package/ngx-image-compress
-
它工作得很好,但是它将图像作为 base64 字符串返回,我需要它作为图像文件,所以我可以将它上传到 firebase,有什么想法吗?
标签: javascript html angular firebase image