我是Angular的初学者,我想知道如何创建Angular 5文件上传部分,我试图找到任何教程或文档,但我在任何地方都看不到任何东西。对此有什么想法吗?我尝试了ng4-files,但它不适用于Angular 5
当前回答
就我个人而言,我使用ngx-material-file-input作为前端,Firebase作为后端。更准确地说,后端是与Cloud Firestore结合的Cloud Storage for Firebase。下面是一个示例,它限制文件不大于20 MB,并且只接受某些文件扩展名。我还使用Cloud Firestore来存储上传文件的链接,但你可以跳过这个。
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>
ts(大小验证器部分)
import { FileValidator } from 'ngx-material-file-input';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
/**
* @constructor
* @description Creates a new instance of this component.
* @param {formBuilder} - an abstraction class object to create a form group control for the contact form.
*/
constructor(
private angularFirestore: AngularFirestore,
private angularFireStorage: AngularFireStorage,
private formBuilder: FormBuilder
) {}
public maxFileSize = 20971520;
public contactForm: FormGroup = this.formBuilder.group({
fileUploader: [
'',
Validators.compose([
FileValidator.maxContentSize(this.maxFileSize),
Validators.maxLength(512),
Validators.minLength(2)
])
]
})
ts(文件上传器部分)
import { AngularFirestore } from '@angular/fire/firestore';
import {
AngularFireStorage,
AngularFireStorageReference,
AngularFireUploadTask
} from '@angular/fire/storage';
import { catchError, finalize } from 'rxjs/operators';
import { throwError } from 'rxjs';
public downloadURL: string[] = [];
/**
* @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'))
}
}
}
其他回答
试试这个
安装
npm install primeng --save
进口
import {FileUploadModule} from 'primeng/primeng';
Html
<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
accept="image/*" auto="auto"></p-fileUpload>
下面是一个上传文件到api的例子:
步骤1:HTML模板
定义文件类型的简单输入标记。为(change)-event添加一个处理选择文件的函数。
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>
步骤2:在TypeScript中处理上传
为所选文件定义一个默认变量。
fileToUpload: File | null = null;
创建你在(change)-event中使用的函数:
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
如果你想处理多文件选择,那么你可以遍历这个文件数组。
现在通过调用file-upload.service创建文件上传函数:
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
第三步:文件上传服务
通过post方法上传文件,你应该使用FormData,因为这样你可以添加文件到http请求。
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
所以,这是一个非常简单的工作例子,我每天都在工作中使用。
在我的情况下,我使用http拦截器,事情是,默认情况下,我的http拦截器设置内容类型头为应用程序/json,但对于文件上传,我使用multer库。 稍微改变一下我的http。interceptor定义,如果请求体是FormData,它会删除头,不触及访问令牌。 下面是一部分代码,它让我很开心。
if (request.body instanceof FormData) {
request = request.clone({ headers: request.headers.delete('Content-Type', 'application/json') });
}
if (request.body instanceof FormData) {
request = request.clone({ headers: request.headers.delete('Accept', 'application/json')});
}
非常简单和最快的方法是使用ng2-file-upload。
通过npm安装ng2-file-upload。NPM I ng2-file-upload——保存
首先在模块中导入模块。
import { FileUploadModule } from 'ng2-file-upload';
Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]
标记:
<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>
在你的组件中:
import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });
这是最简单的用法。要知道所有的权力,这看到演示
在Angular 7/8/9中
来源链接
使用自举表单
<form>
<div class="form-group">
<fieldset class="form-group">
<label>Upload Logo</label>
{{imageError}}
<div class="custom-file fileInputProfileWrap">
<input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
<div class="img-space">
<ng-container *ngIf="isImageSaved; else elseTemplate">
<img [src]="cardImageBase64" />
</ng-container>
<ng-template #elseTemplate>
<img src="./../../assets/placeholder.png" class="img-responsive">
</ng-template>
</div>
</div>
</fieldset>
</div>
<a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>
在组件类中
fileChangeEvent(fileInput: any) {
this.imageError = null;
if (fileInput.target.files && fileInput.target.files[0]) {
// Size Filter Bytes
const max_size = 20971520;
const allowed_types = ['image/png', 'image/jpeg'];
const max_height = 15200;
const max_width = 25600;
if (fileInput.target.files[0].size > max_size) {
this.imageError =
'Maximum size allowed is ' + max_size / 1000 + 'Mb';
return false;
}
if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
this.imageError = 'Only Images are allowed ( JPG | PNG )';
return false;
}
const reader = new FileReader();
reader.onload = (e: any) => {
const image = new Image();
image.src = e.target.result;
image.onload = rs => {
const img_height = rs.currentTarget['height'];
const img_width = rs.currentTarget['width'];
console.log(img_height, img_width);
if (img_height > max_height && img_width > max_width) {
this.imageError =
'Maximum dimentions allowed ' +
max_height +
'*' +
max_width +
'px';
return false;
} else {
const imgBase64Path = e.target.result;
this.cardImageBase64 = imgBase64Path;
this.isImageSaved = true;
// this.previewImagePath = imgBase64Path;
}
};
};
reader.readAsDataURL(fileInput.target.files[0]);
}
}
removeImage() {
this.cardImageBase64 = null;
this.isImageSaved = false;
}
推荐文章
- 如何在Typescript中解析JSON字符串
- TypeScript中的extends和implements有什么区别
- 如何用angular 2路由器重新加载当前路由
- 创建组件与Angular-CLI &将它添加到一个特定的模块
- 迭代Typescript Map
- 定义TypeScript回调类型
- @HostBinding和@HostListener:它们是做什么用的?
- 如何在TypeScript中实现睡眠函数?
- 在Angular 6中生成服务时,为din提供可注入装饰器的目的是什么?
- 返回一个空的Observable
- 为什么——isolatedModules错误被任何导入修复?
- 如何用npm更新TypeScript到最新版本?
- 如何在angular2中调用另一个组件函数
- Angular 2可选的路由参数
- Typescript:在类型“{" a ":字符串上找不到参数类型为'string'的索引签名;}