ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

ng-zorro-antd Upload 拖拽上传(Drag and Drop)实战指南:实现原理、多文件支持与完整示例

ng-zorro-antd Upload 拖拽上传(Drag and Drop)实战指南:实现原理、多文件支持与完整示例 UI组件前端【免费下载链接】ng-zorro-antdAngular UI Component Library based on Ant Design项目地址https://gitcode.com/gh_mirrors/ng/ng-zorro-antd点击查看免费下载导读本文围绕 ng-zorro-antd 的 Upload 组件中拖拽上传Drag and Drop这一核心交互展开。你将学习如何通过一行nzTypedrag把nz-upload从点击选择升级为拖入即传并理解其底层的事件处理、文件过滤与上传管线实现同时掌握nzMultiple多文件上传的适用前提、nzChange状态回调的完整用法最终能够基于真实仓库源码写出可复制的拖拽上传区域。拖拽上传是什么在 ng-zorro-antd 中Upload 组件nz-upload提供两种基础形态由 upload.component.ts 中的nzType输入控制类型定义见 interface.ts 的NzUploadType select | dragnzTypeselect默认点击按钮或区域打开系统文件选择框nzTypedrag把文件直接拖入指定区域完成上传同时保留点击上传能力。拖拽模式非常适合批量导入、附件收集、图片素材库等场景——用户无需先下载文件、再找上传入口直接把文件拖到页面指定区域即可且该区域本身仍可点击唤起文件选择器兼顾两种操作习惯。最小可用示例拖拽上传区域仓库自带官方示例位于 components/upload/demo/drag.ts其核心模板如下nz-upload nzTypedrag [nzMultiple]true nzActionhttps://www.mocky.io/v2/5cc8019d300000980a055e76 (nzChange)handleChange($event) p classant-upload-drag-icon nz-icon nzTypeinbox / /p p classant-upload-textClick or drag file to this area to upload/p p classant-upload-hint Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files /p /nz-upload对应组件类使用 Angular 现代inject()注入NzMessageServiceimport { Component, inject } from angular/core; import { NzMessageService } from ng-zorro-antd/message; import { NzUploadChangeParam, NzUploadModule } from ng-zorro-antd/upload; Component({ selector: nz-demo-upload-drag, template: !-- 上述模板 -- }) export class NzDemoUploadDragComponent { private readonly messageService inject(NzMessageService); handleChange({ file, fileList }: NzUploadChangeParam): void { const status file.status; if (status ! uploading) { console.log(file, fileList); } if (status done) { this.messageService.success(${file.name} file uploaded successfully.); } else if (status error) { this.messageService.error(${file.name} file upload failed.); } } }几点说明nzAction是必选参数见 doc/index.zh-CN.md API 表值为上传地址示例中的地址是官方 demo 使用的 mock 服务实际项目请替换为你的后端接口。它还支持(file) string | Observablestring函数形式可在上传时按文件动态计算地址。模板中三段p是拖拽区的推荐内容结构ant-upload-drag-icon图标、ant-upload-text主文案、ant-upload-hint辅助提示样式由 style/index.less 定义。NzUploadModule需要被 import 到使用组件的模块中或使用 standalone imports 直接引入示例中同时引入NzButtonModule、NzIconModule用于装饰图标。拖拽上传的底层实现原理事件层drop / dragover / dragleave从 upload.component.html 可以看到当nzType drag时组件渲染一个独立的拖拽容器并绑定三个事件div [class]classList() (drop)fileDrop($event) (dragover)fileDrop($event) (dragleave)fileDrop($event) div nz-upload-btn #uploadComp [options]_btnOptions! classant-upload-btn div classant-upload-drag-container ng-content / /div /div /div容器内部嵌入了nz-upload-btn即NzUploadBtnComponent因此拖入的文件最终落到按钮组件的onFileDrop处理函数中见 upload-btn.component.tsonFileDrop(e: DragEvent): void { if (this.options.disabled || e.type dragover) { e.preventDefault(); return; } if (this.options.directory) { this.traverseFileTree(e.dataTransfer!.items); } else { const files: File[] Array.prototype.slice .call(e.dataTransfer!.files) .filter((file: File) this.attrAccept(file, this.options.accept)); if (files.length) { this.uploadFiles(files); } } e.preventDefault(); }关键细节dragover事件仅做preventDefault()阻止浏览器默认的在新标签页打开文件行为并立即返回避免误触发上传nzDirectory开启时走traverseFileTree递归读取DataTransferItemList中的文件夹与子文件夹见 upload-btn.component.ts普通模式下通过e.dataTransfer.files取文件再用attrAccept按nzAccept过滤见 upload-btn.component.ts过滤后调用uploadFiles(files)进入统一的上传管线。状态层dragState 与拖拽高亮NzUploadComponent内部维护dragState并用fileDrop统一接收三种事件见 upload.component.tsprivate dragState?: string; // skip safari bug fileDrop(e: DragEvent): void { if (e.type this.dragState) { return; } this.dragState e.type; this.setClassMap(); }由于dragenter/dragover会高频触发源码用同一事件类型只处理一次的防抖技巧规避 Safari 的 bug。setClassMap见 upload.component.ts会根据状态追加 CSS 类有文件正在上传status uploading→ant-upload-drag-uploading当前处于dragover→ant-upload-drag-hovernzDisabled为真 →ant-upload-disabled。样式上拖拽区的虚线边框在 hover / 拖入时会高亮为主题色.ant-upload-drag-hover使用primary-7普通 hover 使用primary-5见 style/index.less让用户获得清晰的交互反馈。另外在 Firefox 中为防止把文件拖到页面其他区域时打开新标签页组件在ngAfterViewInit里对document.body的drop事件做了全局preventDefault stopPropagation见 upload.component.ts。上传管线从 drop 到 HTTP 请求文件进入uploadFiles后会依次经过过滤器filters→nzBeforeUpload钩子 → 默认HttpClientPOST 或nzCustomRequest见 upload-btn.component.ts。默认的xhr实现见 upload-btn.component.ts会把nzData的键值对写入FormData以nzName默认file作为文件字段名追加文件设置X-Requested-With: XMLHttpRequest请求头用HttpRequest(POST, action, formData, { reportProgress: true })发起上传并监听UploadProgress事件计算percent进度。测试用例 upload.spec.ts 验证了拖拽上传的完整行为nzType设为drag后触发fileDrop的dragover会生成.ant-upload-drag-hover上传中会生成.ant-upload-drag-uploading类。多文件上传nzMultiple 的正确姿势示例文档drag.md明确指出设置nzMultiple后在IE10可以一次上传多个文件。也就是说多选能力依赖浏览器对input typefile multiple的支持HTML5 特性IE10及现代浏览器均支持。实现上NzUploadBtnComponent的模板把multiple属性透传到隐藏的原生 input见 upload-btn.component.htmlinput typefile [attr.id]nzId() #file (change)onChange($event) [attr.accept]options.accept [multiple]options.multiple [style.display]none /示例中同时使用了nzTypedrag与[nzMultiple]true因此既支持一次拖入多个文件也支持按住Ctrl在文件选择框里多选。nzMultiple还与以下参数联动见 upload.component.ts 的zipOptions逻辑nzLimit限制单次最多上传数量仅nzMultiple开启时有效0表示不限开启后组件会自动追加名为limit的过滤器fileList.slice(-nzLimit)nzMaxCount限制列表中的上传总数为1时始终用最新文件替换当前文件打开nzMultiple时如需限制文件大小与类型可配合nzSize单位 KB与nzFileType如image/png,image/jpeg组件同样会以过滤器形式自动注入。监听上传状态nzChange 回调详解拖拽上传同样通过(nzChange)输出事件感知进度完整参数表见 doc/index.zh-CN.md。回调参数结构为{ file: NzUploadFile, // 当前操作的文件对象 fileList: NzUploadFile[], // 当前完整文件列表 event?: { percent: number }, // 上传中的服务端响应含进度高级浏览器支持 type?: string // 回调类型start | progress | success | error | removed }NzUploadChangeParam与NzUploadFile的定义见 interface.ts。其中file.status的取值见UploadFileStatusinterface.tsuploading、done、error、removed文件对象还包含uid唯一标识、name、response服务端响应等字段。组件内部通过onStart / onProgress / onSuccess / onError四个私有回调驱动事件发射见 upload.component.ts上传开始置status uploading并触发type: start进度到达时更新file.percent触发type: progress成功置status done并记录response触发type: success失败置status error触发type: error移除文件则触发type: removed。拖拽上传区域完整可运行模板综合以上内容这里给出一个可直接落到项目中的完整实现含限制与提示请将nzAction替换为你的真实上传接口import { Component } from angular/core; import { NzMessageService } from ng-zorro-antd/message; import { NzUploadChangeParam, NzUploadModule } from ng-zorro-antd/upload; Component({ selector: app-drag-upload, imports: [NzUploadModule], template: nz-upload nzTypedrag [nzMultiple]true [nzLimit]10 [nzSize]2048 nzFileTypeimage/png,image/jpeg,image/gif nzActionhttps://your-server.example/upload (nzChange)handleChange($event) p classant-upload-drag-icon nz-icon nzTypeinbox / /p p classant-upload-text将文件拖到此区域或点击上传/p p classant-upload-hint支持单文件与批量上传单次最多 10 个文件单个文件不超过 2MB仅限图片格式/p /nz-upload }) export class DragUploadComponent { constructor(private messageService: NzMessageService) {} handleChange({ file }: NzUploadChangeParam): void { if (file.status done) { this.messageService.success(${file.name} 上传成功); } else if (file.status error) { this.messageService.error(${file.name} 上传失败); } } }延伸能力与进阶提示限制文件类型/大小除nzAccept透传到原生 input 的 accept 属性外nzFileType、nzSize、nzLimit都以UploadFilter形式在 upload-btn.component.ts 中被串行执行不满足条件的文件会被过滤不会进入上传流程。自定义上传行为需要对接阿里云 OSS 等场景时可用nzCustomRequest覆盖默认HttpClient上传回调参数包含onProgress / onError / onSuccess / data / filename / file / withCredentials / action / headers见 doc/index.zh-CN.md 的nzCustomRequest一节。上传前拦截nzBeforeUpload返回false/Observable(false)即可中止上传也可返回新的File/Blob实现文件压缩、转码后再提交注意 IE9 不支持该方法且务必使用箭头函数绑定this。上传列表样式nzListType支持text、picture、picture-card三种内建样式与拖拽区配合可组合出拖入 → 缩略图列表的完整体验nzShowUploadList可细粒度控制预览/删除/下载图标是否展示。拖拽文件夹设置[nzDirectory]true后拖入文件夹会通过traverseFileTree递归收集其中文件依赖浏览器对webkitdirectory的支持见 upload-btn.component.html。更完整的 API 参数表nzAccept、nzAction、nzBeforeUpload、nzData、nzHeaders、nzShowUploadList、nzWithCredentials等全部输入与事件可查阅 doc/index.zh-CN.md官方还有其他 14 个 demo如picture-card、upload-with-aliyun-oss、transform-file等位于 components/upload/demo 目录可作为进一步参考。小结拖拽上传只需设置nzTypedrag点击上传能力依然保留组件通过drop / dragover / dragleave事件与dragState状态机完成文件接收与高亮反馈底层复用与点击上传完全一致的文件过滤、beforeUpload与 HTTP 上传管线nzMultiple依赖原生input multiple在IE10与现代浏览器可用可与nzLimit、nzMaxCount组合精细控制用(nzChange)监听start / progress / success / error / removed状态即可构建带进度与结果反馈的完整拖拽上传体验。赞分享UI组件前端【免费下载链接】ng-zorro-antdAngular UI Component Library based on Ant Design项目地址https://gitcode.com/gh_mirrors/ng/ng-zorro-antd点击查看免费下载相关推荐Hermes Agent技术融合重构云原生AI架构的新范式Hermes Agent技术融合重构云原生AI架构的新范式 在AI驱动的数字化转型浪潮中技术架构师面临着一个核心挑战如何在保持系统弹性的同时实现AI能力UI组件前端PyQt5 拖放Drag and Drop实战教程QMimeData 数据传输与组件拖拽完整示例PyQt5 拖放Drag and Drop实战教程QMimeData 数据传输与组件拖拽完整示例 本教程基于 PyQt Chinese tutorial文档教程Grafana Pyroscope 1.17 发布说明详解Exemplar 查询、符号化性能与稳定性增强Grafana Pyroscope 1.17 发布说明详解Exemplar 查询、符号化性能与稳定性增强 Grafana Pyroscope 1.17.0 是UI组件前端上一篇从零启动你的第一个开源项目opensource.guide 启动指南详解与发布检查清单下一篇komorebi 配置命令指南用 komorebic configuration 定位与切换静态配置文件创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表