syncfusion-aspnetcore-uploader
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组件。
When to Use This Skill
何时使用本技能
Use this skill when you need to:
- Create file upload forms for images, documents, and media
- Implement asynchronous file uploads with progress feedback
- Validate file types and sizes before upload
- Support drag-and-drop file selection
- Handle multiple file uploads simultaneously
- Process file removal and cleanup
- Build enterprise-grade file management interfaces
- Implement chunk uploads for large files
- Integrate file uploads into HTML forms
- Support paste-to-upload and directory uploads
- Ensure proper file handling and security
当您需要以下功能时,可使用本技能:
- 创建图片、文档和媒体文件的上传表单
- 实现带进度反馈的异步文件上传
- 在上传前验证文件类型和大小
- 支持拖拽选择文件
- 同时处理多文件上传
- 处理文件移除和清理
- 构建企业级文件管理界面
- 实现大文件的分片上传
- 将文件上传集成到HTML表单中
- 支持粘贴上传和目录上传
- 确保文件处理的规范性和安全性
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 |
| 功能 | 适用场景 |
|---|---|
| Asynchronous Upload | 通过SaveUrl/RemoveUrl处理程序实现无阻塞上传 |
| Multiple File Upload | 一次性选择并上传多个文件 |
| Single File Upload | 限制每次选择仅上传一个文件 |
| File Validation | 验证文件扩展名、大小、数量及重复文件 |
| Drag and Drop | 将文件直接拖放到上传区域 |
| Custom Drop Area | 将外部元素定义为拖拽区域 |
| Auto Upload | 自动或手动触发文件上传 |
| Progress Tracking | 通过进度条显示上传进度 |
| File Removal | 通过RemoveUrl处理程序移除已上传文件 |
| Chunk Upload | 将大文件拆分为分片以实现可靠上传 |
| Paste Upload | 从剪贴板上传图片 |
| Directory Upload | 上传整个文件夹及目录结构 |
| Form Integration | 将文件作为表单提交的一部分提交 |
| Templates | 自定义文件列表和按钮外观 |
| Localization | 支持多语言和多文化 |
| Error Handling | 显示自定义上传失败提示信息 |
Documentation Navigation Guide
文档导航指南
Getting Started
快速入门
📄 Read: references/getting-started.md
- Prerequisites and system requirements
- Installing Syncfusion.EJ2.AspNetCore NuGet package
- Configuring TagHelpers in _ViewImports.cshtml
- Adding stylesheets and script resources via CDN
- Registering the script manager
- Creating your first Uploader
- Basic configuration and properties
📄 阅读: references/getting-started.md
- 前提条件和系统要求
- 安装Syncfusion.EJ2.AspNetCore NuGet包
- 在_ViewImports.cshtml中配置TagHelpers
- 通过CDN添加样式表和脚本资源
- 注册脚本管理器
- 创建第一个Uploader组件
- 基础配置和属性
Asynchronous Upload
异步上传
📄 Read: references/async-upload.md
- Configuring SaveUrl and RemoveUrl endpoints
- Single vs multiple file upload modes
- Auto-upload settings and manual upload triggers
- Success and failure event handlers
- Progress tracking and upload lifecycle
- Handling upload cancellation
📄 阅读: references/async-upload.md
- 配置SaveUrl和RemoveUrl端点
- 单文件与多文件上传模式
- 自动上传设置和手动上传触发方式
- 成功和失败事件处理程序
- 进度跟踪和上传生命周期
- 处理上传取消操作
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
- Duplicate file detection and prevention
- Custom validation patterns and error messages
- Validation before and after upload
📄 阅读: references/file-validation.md
- 通过allowed-extensions验证文件类型
- 文件大小限制(min-file-size、max-file-size)
- 最大文件数量限制
- 重复文件检测与阻止
- 自定义验证规则和错误提示信息
- 上传前后的验证
Drag and Drop Support
拖拽支持
📄 Read: references/drag-drop-support.md
- Default drag-and-drop behavior
- Configuring custom drop areas
- Multiple drop zones on single page
- Drag-drop events and event handling
- Paste-to-upload from clipboard
- Directory drag-drop support
📄 阅读: references/drag-drop-support.md
- 默认拖拽行为
- 配置自定义拖拽区域
- 单页面多拖拽区域
- 拖拽事件及事件处理
- 从剪贴板粘贴上传
- 目录拖拽支持
Templates and Styling
模板与样式
📄 Read: references/templates-and-styling.md
- Template property for custom UI
- Button customization and arrangement
- File list item rendering
- CSS class customization
- Theme integration (Fluent, Material, Bootstrap)
- Responsive design patterns
📄 阅读: references/templates-and-styling.md
- 用于自定义UI的Template属性
- 按钮自定义与布局
- 文件列表项渲染
- CSS类自定义
- 主题集成(Fluent、Material、Bootstrap)
- 响应式设计模式
Advanced Patterns
高级模式
📄 Read: references/advanced-patterns.md
- Chunk upload for large files
- Form submission with file uploads
- Directory upload handling
- File removal and cleanup strategies
- Advanced error handling
- Security considerations and CORS
📄 阅读: references/advanced-patterns.md
- 大文件的分片上传
- 表单提交结合文件上传
- 目录上传处理
- 文件移除和清理策略
- 高级错误处理
- 安全考量与CORS配置
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-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
<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-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
<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();
}
}Configuration in _ViewImports.cshtml (one-time setup)
_ViewImports.cshtml中的配置(一次性设置)
html
@addTagHelper *, Syncfusion.EJ2html
@addTagHelper *, Syncfusion.EJ2In _Layout.cshtml (one-time setup)
_Layout.cshtml中的配置(一次性设置)
W012 – Runtime remote-code dependency risk: Loading scripts and styles from an external CDN means a compromised or tampered CDN file would execute in your users' browsers. Mitigate this with one of the two approaches below.Preferred – Self-host the assets (eliminates the runtime remote dependency entirely):
- Copy
and the theme CSS from the NuGet package or a one-time CDN download intoej2.min.js.wwwroot/lib/syncfusion/- Reference them with relative paths — no
attribute needed because the files are served from your own origin.integrityAlternative – CDN with Subresource Integrity (SRI): If you must use the CDN, pin the file with anhash so the browser rejects any tampered version. Compute the hash withintegrityand update it on every version upgrade.openssl dgst -sha384 -binary <file> | openssl base64 -A
W012 – 运行时远程代码依赖风险: 从外部CDN加载脚本和样式意味着,若CDN文件被篡改,将在用户浏览器中执行恶意代码。可通过以下两种方式缓解此风险。推荐方式 – 自行托管资源(完全消除运行时远程依赖):
- 将NuGet包中的
和主题CSS,或一次性从CDN下载的文件复制到ej2.min.js目录下。wwwroot/lib/syncfusion/- 使用相对路径引用这些资源——无需
属性,因为文件从您自己的源服务器提供。integrity替代方式 – 带子资源完整性(SRI)的CDN: 若必须使用CDN,请通过哈希锁定文件,这样浏览器会拒绝任何被篡改的版本。使用integrity计算哈希,并在每次版本升级时更新。openssl dgst -sha384 -binary <file> | openssl base64 -A
Option A — Self-hosted (recommended)
选项A — 自行托管(推荐)
html
<head>
<!-- Served from your own wwwroot — no external runtime dependency -->
<link rel="stylesheet" href="~/lib/syncfusion/fluent.css" />
</head>
<body>
@RenderBody()
<script src="~/lib/syncfusion/ej2.min.js"></script>
<ejs-scripts></ejs-scripts>
</body>html
<head>
<!-- 从您自己的wwwroot提供服务——无外部运行时依赖 -->
<link rel="stylesheet" href="~/lib/syncfusion/fluent.css" />
</head>
<body>
@RenderBody()
<script src="~/lib/syncfusion/ej2.min.js"></script>
<ejs-scripts></ejs-scripts>
</body>Option B — CDN with SRI pinning
选项B — 带SRI锁定的CDN
html
<head>
<!-- integrity hash must match the exact file; regenerate on every version upgrade -->
<link rel="stylesheet"
href="https://cdn.syncfusion.com/ej2/24.1.48/fluent.css"
integrity="sha384-REPLACE_WITH_ACTUAL_HASH_FOR_fluent.css"
crossorigin="anonymous" />
</head>
<body>
@RenderBody()
<script src="https://cdn.syncfusion.com/ej2/24.1.48/dist/ej2.min.js"
integrity="sha384-REPLACE_WITH_ACTUAL_HASH_FOR_ej2.min.js"
crossorigin="anonymous"></script>
<ejs-scripts></ejs-scripts>
</body>html
<head>
<!-- integrity哈希必须与文件完全匹配;每次版本升级时重新生成 -->
<link rel="stylesheet"
href="https://cdn.syncfusion.com/ej2/24.1.48/fluent.css"
integrity="sha384-REPLACE_WITH_ACTUAL_HASH_FOR_fluent.css"
crossorigin="anonymous" />
</head>
<body>
@RenderBody()
<script src="https://cdn.syncfusion.com/ej2/24.1.48/dist/ej2.min.js"
integrity="sha384-REPLACE_WITH_ACTUAL_HASH_FOR_ej2.min.js"
crossorigin="anonymous"></script>
<ejs-scripts></ejs-scripts>
</body>Common Patterns
常见模式
Pattern 1: Multiple File Upload with Progress
模式1:带进度跟踪的多文件上传
html
<ejs-uploader id="multiUploader"
allowed-extensions=".jpg,.png,.pdf,.doc,.docx"
max-file-size="5242880"
auto-upload="false"
multiple="true"
uploading="onUploading"
success="onSuccess"
failure="onFailure">
<e-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
</ejs-uploader>
<script>
function onUploading(args) {
console.log('Uploading: ' + args.file.name);
console.log('Progress: ' + (args.percentComplete * 100) + '%');
}
function onSuccess(args) {
if (args.operation === 'upload') {
console.log(args.file.name + ' uploaded successfully');
}
}
function onFailure(args) {
console.log('Upload failed: ' + args.response);
}
</script>html
<ejs-uploader id="multiUploader"
allowed-extensions=".jpg,.png,.pdf,.doc,.docx"
max-file-size="5242880"
auto-upload="false"
multiple="true"
uploading="onUploading"
success="onSuccess"
failure="onFailure">
<e-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
</ejs-uploader>
<script>
function onUploading(args) {
console.log('Uploading: ' + args.file.name);
console.log('Progress: ' + (args.percentComplete * 100) + '%');
}
function onSuccess(args) {
if (args.operation === 'upload') {
console.log(args.file.name + ' uploaded successfully');
}
}
function onFailure(args) {
console.log('Upload failed: ' + args.response);
}
</script>Pattern 2: Single File Upload with Validation
模式2:带验证的单文件上传
html
<ejs-uploader id="singleUploader"
allowed-extensions=".jpg,.png,.jpeg"
max-file-size="2097152"
multiple="false"
selected="onFileSelected"
auto-upload="true">
<e-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
</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"
allowed-extensions=".jpg,.png,.jpeg"
max-file-size="2097152"
multiple="false"
selected="onFileSelected"
auto-upload="true">
<e-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
</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"
drop-area="#dropArea"
auto-upload="true">
<e-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
</ejs-uploader>html
<div id="dropArea" style="border: 2px dashed #ccc; padding: 20px; min-height: 200px;">
Drop files here
</div>
<ejs-uploader id="uploader"
drop-area="#dropArea"
auto-upload="true">
<e-async-settings save-url="Home/Save" remove-url="Home/Remove"></e-async-settings>
</ejs-uploader>Key Properties
核心属性
| Property | Type | Default | Purpose |
|---|---|---|---|
| allowed-extensions | string | "" | File types to allow (e.g., ".jpg,.png") |
| max-file-size | long | 28.4MB | Maximum file size in bytes |
| min-file-size | long | 0 | Minimum file size in bytes |
| multiple | bool | true | Allow multiple file selection |
| auto-upload | bool | true | Upload files automatically after selection |
| save-url | string | "" | URL handler for saving files |
| remove-url | string | "" | URL handler for removing files |
| drop-area | string | "" | CSS selector for custom drop area |
| 属性 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| allowed-extensions | string | "" | 允许上传的文件类型(例如:".jpg,.png") |
| max-file-size | long | 28.4MB | 最大文件大小(字节) |
| min-file-size | long | 0 | 最小文件大小(字节) |
| multiple | bool | true | 是否允许选择多个文件 |
| auto-upload | bool | true | 选择文件后是否自动上传 |
| save-url | string | "" | 用于保存文件的URL处理程序 |
| remove-url | string | "" | 用于移除文件的URL处理程序 |
| drop-area | string | "" | 自定义拖拽区域的CSS选择器 |
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组件。