在Angular应用程序中,我有一个带有文件上传输入的联系表。如果合并的文件大于20 MB,则在前端输入的文件上传不允许发送联系表。 有什么方法可以在Cloud Storage for Firebase中实现相同的逻辑吗?目前我只能限制20 MB,但是对于每个文件,即如果某人将上传10个文件,每19 MB /人将无法发送表单,但是文件将发送到我不需要的无服务器后端。
contact.component.html
<mat-form-field>
<!--
Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side.
-->
<ngx-mat-file-input
[accept]="[
'.doc',
'.docx',
'.jpg',
'.jpeg',
'.pdf',
'.png',
'.xls',
'.xlsx'
]"
(change)="uploadFile($event)"
formControlName="fileUploader"
multiple
aria-label="Here you can add additional files about your project, which can be helpeful for us."
placeholder="Additional files"
title="Additional files"
type="file"
>
</ngx-mat-file-input>
<mat-icon matSuffix>folder</mat-icon>
<mat-hint
>Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
maximum files upload size: 20 MB.
</mat-hint>
<!--
Non-null assertion operators are required to let know the compiler that this value is not empty and exists.
-->
<mat-error
*ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
>
This size is too large,
<strong
>maximum acceptable upload size is
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.maxSize | byteFormat
}}</strong
>
(uploaded size:
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.actualSize | byteFormat
}}).
</mat-error>
</mat-form-field>
contact.component.ts (大小验证器)
public maxFileSize = 20971520;
public contactForm: FormGroup = this.formBuilder.group({
fileUploader: [
'',
Validators.compose([
FileValidator.maxContentSize(this.maxFileSize),
Validators.maxLength(512),
Validators.minLength(2)
])
].toString()
})
contact.component.ts (文件上传器)
/**
* @description Upload additional files to Cloud Firestore and get URL to the files.
* @param {event} - object of sent files.
* @returns {void}
*/
public uploadFile(event: any): void {
// Iterate through all uploaded files.
for (let i = 0; i < event.target.files.length; i++) {
const randomId = Math.random()
.toString(36)
.substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.
const file = event.target.files[i]; // Get each uploaded file.
// Get file reference.
const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
randomId
);
// Create upload task.
const task: AngularFireUploadTask = this.angularFireStorage.upload(
randomId,
file
);
// Upload file to Cloud Firestore.
task
.snapshotChanges()
.pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe((downloadURL: string) => {
this.angularFirestore
.collection(process.env.FIRESTORE_COLLECTION_FILES!) // Non-null assertion operator is required to let know the compiler that this value is not empty and exists.
.add({ downloadURL: downloadURL });
this.downloadURL.push(downloadURL);
});
}),
catchError((error: any) => {
return throwError(error);
})
)
.subscribe();
}
}
storage.rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read; // Required in order to send this as attachment.
// Allow write files Firebase Storage, only if:
// 1) File is no more than 20MB
// 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
allow write: if request.resource.size <= 20 * 1024 * 1024
&& (request.resource.contentType.matches('application/msword')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| request.resource.contentType.matches('image/jpg')
|| request.resource.contentType.matches('image/jpeg')
|| request.resource.contentType.matches('application/pdf')
|| request.resource.contentType.matches('image/png')
|| request.resource.contentType.matches('application/vnd.ms-excel')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
}
}
}
答案 0 :(得分:1)
Cloud Storage for Firebase中的限制安全规则分别适用于每个文件/对象,不适用于整个操作。在Cloud Storage规则的上下文中,这种限制类型也没有多大意义,因为用户可以启动另一个操作来上传其他文件。
要考虑的一些选项:
如果您对用户上传的文件名进行硬编码(这也意味着您将限制他们可以上传的文件数),并为每个特定用户创建文件文件夹,则可以确定用户文件夹中所有文件的总和,从而以这种方式限制总和。
或者,您可以在客户端上将所有文件压缩在一起,然后上传生成的存档。在这种情况下,安全规则可以强制执行该文件的最大大小。
当然,在这两种情况下,您都可以包含客户端JavaScript代码来检查组合文件的最大大小。恶意用户可以轻松绕过此JavaScript,但是大多数用户不是恶意用户,并且感谢您通过阻止无论如何都会被拒绝的上传来节省带宽。
您还可以使用HTTPS Cloud Function作为上传目标,然后仅在满足要求时将文件传递到Cloud Storage。
或者,您可以使用云功能,该云功能在从用户上传时触发,并在更改后为该用户验证文件。此时,您可以纠正这种情况。
许多这些情况要求(或更好地工作)您具有一个结构,从路径可以看到哪个用户上载了每个文件。有关此结构的更多信息,请参见user-private files上的文档。