syncfusion-aspnetcore-inputs
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Uploader in ASP.NET Core
在ASP.NET Core中实现Uploader组件
The Uploader is a powerful file upload component for ASP.NET Core that handles file selection, validation, asynchronous uploads, drag-and-drop support, and progress tracking. This skill guides you through implementing Uploader in ASP.NET Core applications using Syncfusion's TagHelper syntax.
Uploader是适用于ASP.NET Core的强大文件上传组件,可处理文件选择、验证、异步上传、拖放支持以及进度跟踪。本指南将引导你使用Syncfusion的TagHelper语法在ASP.NET Core应用中实现Uploader组件。
Key Features
核心特性
| Feature | Use Case |
|---|---|
| Asynchronous Upload | Non-blocking uploads with SaveUrl/RemoveUrl handlers |
| Multiple File Upload | Select and upload many files at once |
| Single File Upload | Restrict to one file per selection |
| File Validation | Validate extensions, size, count, duplicates |
| Drag and Drop | Drop files directly onto uploader area |
| Custom Drop Area | Define external elements as drop zones |
| Auto Upload | Upload files automatically or manually |
| Progress Tracking | Display upload progress with progress bar |
| File Removal | Remove uploaded files with RemoveUrl handler |
| Chunk Upload | Break large files into chunks for reliable upload |
| Paste Upload | Upload images from clipboard |
| Directory Upload | Upload entire folders and directory structure |
| Form Integration | Submit files as part of form submission |
| Templates | Customize file list and button appearance |
| Localization | Support multiple languages and cultures |
| Error Handling | Display upload failures with custom messages |
| 特性 | 使用场景 |
|---|---|
| 异步上传 | 借助SaveUrl/RemoveUrl处理器实现无阻塞上传 |
| 多文件上传 | 一次性选择并上传多个文件 |
| 单文件上传 | 限制每次选择仅上传一个文件 |
| 文件验证 | 验证文件扩展名、大小、数量及重复文件 |
| 拖放功能 | 直接将文件拖放到上传区域 |
| 自定义拖放区域 | 将外部元素定义为拖放区 |
| 自动上传 | 自动或手动触发文件上传 |
| 进度跟踪 | 通过进度条显示上传进度 |
| 文件移除 | 借助RemoveUrl处理器移除已上传文件 |
| 分片上传 | 将大文件拆分为分片以实现可靠上传 |
| 粘贴上传 | 从剪贴板上传图片 |
| 目录上传 | 上传整个文件夹及目录结构 |
| 表单集成 | 将文件作为表单提交的一部分进行提交 |
| 模板定制 | 自定义文件列表和按钮外观 |
| 本地化 | 支持多种语言和区域文化 |
| 错误处理 | 显示上传失败信息并支持自定义提示 |
Documentation Navigation Guide
文档导航指南
API Reference
API参考
📄 Read: references/api.md
- Complete list of all properties with TagHelper attribute names and defaults
- All events with callback argument details
- UploaderAsyncSettings sub-properties (save-url, remove-url, chunk-size, retry-count, retry-after-delay)
- UploaderButtonsProps sub-properties (browse, upload, clear)
- Preloaded files configuration (e-uploader-files / e-uploader-uploadedfiles)
📄 阅读: references/api.md
- 包含所有属性的完整列表,以及TagHelper属性名称和默认值
- 所有事件及回调参数详情
- UploaderAsyncSettings子属性(save-url、remove-url、chunk-size、retry-count、retry-after-delay)
- UploaderButtonsProps子属性(browse、upload、clear)
- 预加载文件配置(e-uploader-files / e-uploader-uploadedfiles)
Getting Started
快速入门
📄 Read: references/getting-started.md
- Prerequisites and system requirements
- Installing Syncfusion.EJ2.AspNet.Core NuGet package
- Configuring TagHelpers in _ViewImports.cshtml
- Adding stylesheets and script resources via CDN
- Registering the script manager ()
<ejs-scripts> - Creating your first Uploader
- Basic configuration and properties
📄 阅读: references/getting-started.md
- 前提条件和系统要求
- 安装Syncfusion.EJ2.AspNet.Core NuGet包
- 在_ViewImports.cshtml中配置TagHelpers
- 通过CDN添加样式表和脚本资源
- 注册脚本管理器()
<ejs-scripts> - 创建你的第一个Uploader组件
- 基础配置和属性
Asynchronous Upload
异步上传
📄 Read: references/async-upload.md
- Configuring SaveUrl and RemoveUrl endpoints
- Single vs multiple file upload modes ()
multiple - Sequential upload ()
sequential-upload - Auto-upload settings and manual upload triggers ()
auto-upload - Success and failure event handlers (,
success)failure - Progress tracking via event (
progress)args.e.loaded / args.e.total - Upload cancellation and retry
- Adding custom headers via event
uploading
📄 阅读: references/async-upload.md
- 配置SaveUrl和RemoveUrl端点
- 单文件与多文件上传模式()
multiple - 顺序上传()
sequential-upload - 自动上传设置和手动上传触发()
auto-upload - 成功和失败事件处理器(、
success)failure - 通过事件跟踪进度(
progress)args.e.loaded / args.e.total - 上传取消和重试
- 通过事件添加自定义请求头
uploading
File Validation
文件验证
📄 Read: references/file-validation.md
- File type validation with
allowed-extensions - File size constraints (,
min-file-size)max-file-size - Maximum file count restrictions via event
selected - Duplicate file detection and prevention
- Custom validation messages using
ej.base.L10n.load - Validation before and after upload
📄 阅读: references/file-validation.md
- 使用验证文件类型
allowed-extensions - 文件大小限制(、
min-file-size)max-file-size - 通过事件限制最大文件数量
selected - 重复文件检测与阻止
- 使用自定义验证提示信息
ej.base.L10n.load - 上传前后的验证
Drag and Drop Support
拖放支持
📄 Read: references/drag-drop-support.md
- Default drag-and-drop behavior
- Configuring custom drop areas ()
drop-area - Multiple drop zones on single page
- File filtering on drop using and
allowed-extensionseventselected - Paste-to-upload from clipboard (native JS clipboard events)
- Directory drag-drop support ()
directory-upload
📄 阅读: references/drag-drop-support.md
- 默认拖放行为
- 配置自定义拖放区域()
drop-area - 单页面多拖放区
- 通过和
allowed-extensions事件过滤拖放文件selected - 剪贴板粘贴上传(原生JS剪贴板事件)
- 目录拖放支持()
directory-upload
Templates and Styling
模板与样式定制
📄 Read: references/templates-and-styling.md
- property for custom file list item UI (
template,${name},${size},${type})${statusText} - Button customization via
<e-upload-buttons browse="" upload="" clear=""> - for fully custom file lists
show-file-list - CSS class customization ()
css-class - Theme integration (Fluent, Material, Bootstrap)
- Responsive design patterns
📄 阅读: references/templates-and-styling.md
- 属性用于自定义文件列表项UI(
template、${name}、${size}、${type})${statusText} - 通过自定义按钮
<e-upload-buttons browse="" upload="" clear=""> - 用于完全自定义文件列表
show-file-list - CSS类定制()
css-class - 主题集成(Fluent、Material、Bootstrap)
- 响应式设计模式
Advanced Patterns
高级模式
📄 Read: references/advanced-patterns.md
- Chunk upload for large files (,
chunk-size,retry-count)retry-after-delay - Correct server-side chunk handling (,
chunk-indexform keys)total-chunk - Pause/resume chunk upload
- Form submission with file uploads ()
autoUpload="false" - Directory upload handling ()
directory-upload - File removal and cleanup strategies
- Advanced error handling
- Security considerations (path traversal prevention, MIME validation)
📄 阅读: references/advanced-patterns.md
- 大文件分片上传(、
chunk-size、retry-count)retry-after-delay - 服务端分片处理(、
chunk-index表单键)total-chunk - 分片上传暂停/恢复
- 表单提交结合文件上传()
autoUpload="false" - 目录上传处理()
directory-upload - 文件移除与清理策略
- 高级错误处理
- 安全注意事项(路径遍历防护、MIME验证)
Quick Start Example
快速入门示例
Basic Uploader with Async Upload (TagHelper)
带异步上传的基础Uploader(TagHelper)
html
<!-- Views/Home/Index.cshtml -->
<div class="form-group">
<ejs-uploader id="uploader">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
<e-upload-files></e-upload-files>
</ejs-uploader>
</div>
<div id="uploadedFiles"></div>html
<!-- Views/Home/Index.cshtml -->
<div class="form-group">
<ejs-uploader id="uploader">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
<e-upload-files></e-upload-files>
</ejs-uploader>
</div>
<div id="uploadedFiles"></div>Configuration in HomeController.cs
HomeController.cs中的配置
csharp
using Microsoft.AspNetCore.Mvc;
using System.IO;
public class HomeController : Controller
{
private readonly IWebHostEnvironment _webHostEnvironment;
public HomeController(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
[HttpPost]
public IActionResult Save(IFormFile[] uploader)
{
if (uploader != null && uploader.Length > 0)
{
string uploadPath = Path.Combine(_webHostEnvironment.WebRootPath, "Uploads");
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
foreach (IFormFile file in uploader)
{
string filePath = Path.Combine(uploadPath, file.FileName);
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
}
}
return Ok();
}
[HttpPost]
public IActionResult Remove(string[] files)
{
string uploadPath = Path.Combine(_webHostEnvironment.WebRootPath, "Uploads");
foreach (string file in files)
{
string filePath = Path.Combine(uploadPath, file);
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);
}
return Ok();
}
}csharp
using Microsoft.AspNetCore.Mvc;
using System.IO;
public class HomeController : Controller
{
private readonly IWebHostEnvironment _webHostEnvironment;
public HomeController(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
[HttpPost]
public IActionResult Save(IFormFile[] uploader)
{
if (uploader != null && uploader.Length > 0)
{
string uploadPath = Path.Combine(_webHostEnvironment.WebRootPath, "Uploads");
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
foreach (IFormFile file in uploader)
{
string filePath = Path.Combine(uploadPath, file.FileName);
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
}
}
return Ok();
}
[HttpPost]
public IActionResult Remove(string[] files)
{
string uploadPath = Path.Combine(_webHostEnvironment.WebRootPath, "Uploads");
foreach (string file in files)
{
string filePath = Path.Combine(uploadPath, file);
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);
}
return Ok();
}
}In _ViewImports.cshtml (one-time setup)
在_ViewImports.cshtml中配置(一次性设置)
html
@addTagHelper *, Syncfusion.EJ2html
@addTagHelper *, Syncfusion.EJ2In _Layout.cshtml (one-time setup)
在_Layout.cshtml中配置(一次性设置)
html
<head>
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/33.1.44/fluent.css" />
<script src="https://cdn.syncfusion.com/ej2/33.1.44/dist/ej2.min.js"></script>
</head>
<body>
@RenderBody()
<ejs-scripts></ejs-scripts>
</body>html
<head>
<link rel="stylesheet" href="https://cdn.syncfusion.com/ej2/33.1.44/fluent.css" />
<script src="https://cdn.syncfusion.com/ej2/33.1.44/dist/ej2.min.js"></script>
</head>
<body>
@RenderBody()
<ejs-scripts></ejs-scripts>
</body>Common Patterns
常见模式
Pattern 1: Multiple File Upload with Progress
模式1:带进度跟踪的多文件上传
html
<ejs-uploader id="multiUploader"
allowedExtensions=".jpg,.png,.pdf,.doc,.docx"
maxFileSize="5242880"
autoUpload="false"
multiple="true"
progress="onProgress"
success="onSuccess"
failure="onFailure">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
</ejs-uploader>
<script>
function onProgress(args) {
console.log('Uploading: ' + args.file.name);
let percent = Math.round((args.e.loaded / args.e.total) * 100);
console.log('Progress: ' + percent + '%');
}
function onSuccess(args) {
if (args.operation === 'upload') {
console.log(args.file.name + ' uploaded successfully');
}
}
function onFailure(args) {
console.log('Upload failed: ' + args.statusCode + ' | ' + args.response);
}
</script>html
<ejs-uploader id="multiUploader"
allowedExtensions=".jpg,.png,.pdf,.doc,.docx"
maxFileSize="5242880"
autoUpload="false"
multiple="true"
progress="onProgress"
success="onSuccess"
failure="onFailure">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
</ejs-uploader>
<script>
function onProgress(args) {
console.log('Uploading: ' + args.file.name);
let percent = Math.round((args.e.loaded / args.e.total) * 100);
console.log('Progress: ' + percent + '%');
}
function onSuccess(args) {
if (args.operation === 'upload') {
console.log(args.file.name + ' uploaded successfully');
}
}
function onFailure(args) {
console.log('Upload failed: ' + args.statusCode + ' | ' + args.response);
}
</script>Pattern 2: Single File Upload with Validation
模式2:带验证的单文件上传
html
<ejs-uploader id="singleUploader"
allowedExtensions=".jpg,.png,.jpeg"
maxFileSize="2097152"
multiple="false"
selected="onFileSelected"
autoUpload="true">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
</ejs-uploader>
<script>
function onFileSelected(args) {
if (args.filesData.length > 1) {
args.filesData.splice(1);
alert('Only one file can be selected');
}
}
</script>html
<ejs-uploader id="singleUploader"
allowedExtensions=".jpg,.png,.jpeg"
maxFileSize="2097152"
multiple="false"
selected="onFileSelected"
autoUpload="true">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
</ejs-uploader>
<script>
function onFileSelected(args) {
if (args.filesData.length > 1) {
args.filesData.splice(1);
alert('Only one file can be selected');
}
}
</script>Pattern 3: Drag-Drop with Custom Area
模式3:带自定义区域的拖放上传
html
<div id="dropArea" style="border: 2px dashed #ccc; padding: 20px; min-height: 200px;">
Drop files here
</div>
<ejs-uploader id="uploader"
dropArea="#dropArea"
autoUpload="true">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
</ejs-uploader>html
<div id="dropArea" style="border: 2px dashed #ccc; padding: 20px; min-height: 200px;">
Drop files here
</div>
<ejs-uploader id="uploader"
dropArea="#dropArea"
autoUpload="true">
<e-uploader-asyncsettings saveUrl="Home/Save" removeUrl="Home/Remove"></e-uploader-asyncsettings>
</ejs-uploader>Key Properties
核心属性
| Property | TagHelper Attribute | Type | Default | Purpose |
|---|---|---|---|---|
| | string | | File types to allow (e.g., |
| | double | | Maximum file size in bytes |
| | double | | Minimum file size in bytes |
| | bool | | Allow multiple file selection |
| | bool | | Upload files automatically after selection |
| | bool | | Upload files one after another |
| | string | null | CSS selector for custom drop area |
| | bool | | Allow folder/directory selection |
| | bool | | Show/hide the default file list |
| | string | null | Custom HTML template for file list items |
| | string | | Additional CSS classes on root element |
| | bool | | Right-to-left rendering |
| | string | | Localization culture code |
AsyncSettings Sub-Properties (set via ):
<e-uploader-asyncsettings>| Property | TagHelper Attribute | Default | Purpose |
|---|---|---|---|
| | | Server endpoint for saving uploaded files |
| | | Server endpoint for removing uploaded files |
| | | Chunk size in bytes; enables chunk upload when > 0 |
| | | Number of retry attempts on chunk failure |
| | | Delay (ms) before chunk retry |
| 属性 | TagHelper属性 | 类型 | 默认值 | 用途 |
|---|---|---|---|---|
| | string | | 允许的文件类型(例如: |
| | double | | 最大文件大小(字节) |
| | double | | 最小文件大小(字节) |
| | bool | | 是否允许选择多个文件 |
| | bool | | 文件选择后是否自动上传 |
| | bool | | 是否按顺序上传文件 |
| | string | null | 自定义拖放区域的CSS选择器 |
| | bool | | 是否允许选择文件夹/目录 |
| | bool | | 是否显示默认文件列表 |
| | string | null | 文件列表项的自定义HTML模板 |
| | string | | 根元素的额外CSS类 |
| | bool | | 是否启用从右到左渲染 |
| | string | | 本地化区域代码 |
AsyncSettings子属性(通过设置):
<e-uploader-asyncsettings>| 属性 | TagHelper属性 | 默认值 | 用途 |
|---|---|---|---|
| | | 保存上传文件的服务端端点 |
| | | 移除已上传文件的服务端端点 |
| | | 分片大小(字节);大于0时启用分片上传 |
| | | 分片上传失败后的重试次数 |
| | | 分片重试前的延迟时间(毫秒) |
Common Use Cases
常见使用场景
Use Case 1: Profile Picture Upload
场景1:头像上传
- Single file, image only, auto-upload
- Reference: references/advanced-patterns.md
- 单文件、仅支持图片、自动上传
- 参考:references/advanced-patterns.md
Use Case 2: Document Management
场景2:文档管理
- Multiple files, validation, chunk upload for large files
- Reference: references/async-upload.md
- 多文件、验证、大文件分片上传
- 参考:references/async-upload.md
Use Case 3: Bulk Import
场景3:批量导入
- Directory upload, form submission, error handling
- Reference: references/advanced-patterns.md
- 目录上传、表单提交、错误处理
- 参考:references/advanced-patterns.md
Use Case 4: Media Gallery
场景4:媒体图库
- Multiple uploads, custom templates, drag-drop
- Reference: references/templates-and-styling.md
Next Step: Read references/getting-started.md to begin implementing Uploader in your ASP.NET Core application.
- 多文件上传、自定义模板、拖放功能
- 参考:references/templates-and-styling.md
下一步: 阅读references/getting-started.md开始在你的ASP.NET Core应用中实现Uploader组件。