0.前言
项目前端使用的组件是Ant Design。最近正好调试项目看到使用nz-uoload进行文件上传。但是要求限制文件上传的类型。这篇文章简单记录一下过程。
前台用的angular+Ant Design for Angular
1.HTML文件
<nz-upload [(nzFileList)]="fileList_product" [nzAccept]="fileType" [nzBeforeUpload]="beforeUploadProduct" [nzPreview]="handlePreview" [nzShowUploadList]="false" (nzChange)="handleChange($event)" style="float: right;"> <button nz-button nzType="primary"> <i class="anticon anticon-upload"></i><span>选择上传文件</span> </button> </nz-upload>
nzAccept 是可以接收的文件类型,
nzBeforeUpload 是再上传之前的文件检查,这是今天主要改动的地方
nzPreview 是预览文件方法
首先说下nzAccept,它表示上传的默认文件类型。在ts文件中可以参考下面的写法
fileType: string = '.doc,docx,.pdf,rar,.xlsx,.xls'; //文件类型
但是,问题来了,这个只能保证你默认选的文件类型是上面这些,不能保证用户选择全部文件类型。如下图:
可以看到,默认的文件类型确实是我们上面定义的哪些,但是如果用户在这个地方选择了所有文件,那么上面的文件类型限制就没用了。我们还是要想办法限制用户上传的文件类型。
2.限制文件类型的思路
主要说一下在前端限制上传文件类型的思路。一种是利用上传上来的文件类型直接判断(因为上面的操作无法限制上传的类型)。主要改动的地方是nzBeforeUpload方法。另外一种是判断文件的后缀。
先说第一种:
import { Component, OnInit, TemplateRef } from '@angular/core'; import { UploadFile, } from 'ng-zorro-antd'; import { Observable, Observer } from 'rxjs'; @Component({ selector: 'xxx', templateUrl: './xxx.component.html', styleUrls: ['./xxx.component.less'] }) export class AddComponent implements OnInit { constructor() { } ngOnInit() { } beforeUploadProduct = (file: UploadFile) => new Observable((observer: Observer<boolean>) => { const isType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif'; debugger if (!isType) { console.log('只支持word、excel、pdf、rar类型!'); observer.complete(); return; } }); }
这里面的文件类型是固定的,可以参考下面的文件类型来使用:
office为 2007版本以后的一些 文件限制类型的 属性值
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.sldx application/vnd.openxmlformats-officedocument.presentationml.slide
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.xlsm application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.doc application/msword
.xls application/vnd.ms-excel
其他的常用的:
.3gpp audio/3gpp, video/3gpp 3GPP Audio/Video
*.ac3 audio/ac3 AC3 Audio
*.asf allpication/vnd.ms-asf Advanced Streaming Format
*.au audio/basic AU Audio
*.css text/css Cascading Style Sheets
*.csv text/csv Comma Separated Values
*.doc application/msword MS Word Document
*.dot application/msword MS Word Template
*.dtd application/xml-dtd Document Type Definition
*.dwg image/vnd.dwg AutoCAD Drawing Database
*.dxf image/vnd.dxf AutoCAD Drawing Interchange Format
*.gif image/gif Graphic Interchange Format
*.htm text/html HyperText Markup Language
*.html text/html HyperText Markup Language
*.jp2 image/jp2 JPEG-2000
*.jpe image/jpeg JPEG
*.jpeg image/jpeg JPEG
*.jpg image/jpeg JPEG
*.js text/javascript, application/javascript JavaScript
*.json application/json JavaScript Object Notation
*.mp2 audio/mpeg, video/mpeg MPEG Audio/Video Stream, Layer II
*.mp3 audio/mpeg MPEG Audio Stream, Layer III
*.mp4 audio/mp4, video/mp4 MPEG-4 Audio/Video
*.mpeg video/mpeg MPEG Video Stream, Layer II
*.mpg video/mpeg MPEG Video Stream, Layer II
*.mpp application/vnd.ms-project MS Project Project
*.ogg application/ogg, audio/ogg Ogg Vorbis
*.pdf application/pdf Portable Document Format
*.png image/png Portable Network Graphics
*.pot application/vnd.ms-powerpoint MS PowerPoint Template
*.pps application/vnd.ms-powerpoint MS PowerPoint Slideshow
*.ppt application/vnd.ms-powerpoint MS PowerPoint Presentation
*.rtf application/rtf, text/rtf Rich Text Format
*.svf image/vnd.svf Simple Vector Format
*.tif image/tiff Tagged Image Format File
*.tiff image/tiff Tagged Image Format File
*.txt text/plain Plain Text
*.wdb application/vnd.ms-works MS Works Database
*.wps application/vnd.ms-works Works Text Document
*.xhtml application/xhtml+xml Extensible HyperText Markup Language
*.xlc application/vnd.ms-excel MS Excel Chart
*.xlm application/vnd.ms-excel MS Excel Macro
*.xls application/vnd.ms-excel MS Excel Spreadsheet
*.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
*.xlt application/vnd.ms-excel MS Excel Template
*.xlw application/vnd.ms-excel MS Excel Workspace
*.xml text/xml, application/xml Extensible Markup Language
*.zip aplication/zip Compressed Archive
第一种有个小问题,实际操作的时候,上传了一个rar文件,发现程序读不出来,然后放弃了第一种方法, 用第二种方法来写:
然后函数改成下面这样:
beforeUploadProduct = (file: UploadFile) => new Observable((observer: Observer<boolean>) => { //上传文件的后缀进行判断 const isType=[""] file.name.lastIndexOf(".") const fileType = file.name.substring(file.name.lastIndexOf("."),file.name.length) //从后往前截取文类型 if(fileType==".doc"||fileType==".docx"||fileType==".pdf"||fileType==".rar"||fileType==".xlsx"||fileType==".xls"){ observer.next(true); observer.complete(); }else{ console.log('只支持word、excel、pdf、rar类型!'); observer.complete(); return; } });
3.限制文件大小
参考代码如下:
beforeUploadProduct = (file: UploadFile) => new Observable((observer: Observer<boolean>) => { const isLt2M = file.size! / 1024 / 1024 < 2; if (!isLt2M) { console.log('图片大小不要超过2MB!'); observer.complete(); return; } });
我们读取出来文件的大小,直接判断就行。