syncfusion-aspnetcore-inputs

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing 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

核心特性

FeatureUse Case
Asynchronous UploadNon-blocking uploads with SaveUrl/RemoveUrl handlers
Multiple File UploadSelect and upload many files at once
Single File UploadRestrict to one file per selection
File ValidationValidate extensions, size, count, duplicates
Drag and DropDrop files directly onto uploader area
Custom Drop AreaDefine external elements as drop zones
Auto UploadUpload files automatically or manually
Progress TrackingDisplay upload progress with progress bar
File RemovalRemove uploaded files with RemoveUrl handler
Chunk UploadBreak large files into chunks for reliable upload
Paste UploadUpload images from clipboard
Directory UploadUpload entire folders and directory structure
Form IntegrationSubmit files as part of form submission
TemplatesCustomize file list and button appearance
LocalizationSupport multiple languages and cultures
Error HandlingDisplay 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
    progress
    event (
    args.e.loaded / args.e.total
    )
  • Upload cancellation and retry
  • Adding custom headers via
    uploading
    event
📄 阅读: 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
    selected
    event
  • 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
    allowed-extensions
    and
    selected
    event
  • 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
  • template
    property for custom file list item UI (
    ${name}
    ,
    ${size}
    ,
    ${type}
    ,
    ${statusText}
    )
  • Button customization via
    <e-upload-buttons browse="" upload="" clear="">
  • show-file-list
    for fully custom file lists
  • CSS class customization (
    css-class
    )
  • Theme integration (Fluent, Material, Bootstrap)
  • Responsive design patterns
📄 阅读: references/templates-and-styling.md
  • template
    属性用于自定义文件列表项UI(
    ${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-index
    ,
    total-chunk
    form keys)
  • 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.EJ2
html
@addTagHelper *, Syncfusion.EJ2

In _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

核心属性

PropertyTagHelper AttributeTypeDefaultPurpose
AllowedExtensions
allowedExtensions
string
""
File types to allow (e.g.,
".jpg,.png"
)
MaxFileSize
maxFileSize
double
30000000
Maximum file size in bytes
MinFileSize
minFileSize
double
0
Minimum file size in bytes
Multiple
multiple
bool
true
Allow multiple file selection
AutoUpload
autoUpload
bool
true
Upload files automatically after selection
SequentialUpload
sequentialUpload
bool
false
Upload files one after another
DropArea
dropArea
stringnullCSS selector for custom drop area
DirectoryUpload
directoryUpload
bool
false
Allow folder/directory selection
ShowFileList
showFileList
bool
true
Show/hide the default file list
Template
template
stringnullCustom HTML template for file list items
CssClass
cssClass
string
""
Additional CSS classes on root element
EnableRtl
enableRtl
bool
false
Right-to-left rendering
Locale
locale
string
""
Localization culture code
AsyncSettings Sub-Properties (set via
<e-uploader-asyncsettings>
):
PropertyTagHelper AttributeDefaultPurpose
SaveUrl
saveUrl
""
Server endpoint for saving uploaded files
RemoveUrl
removeUrl
""
Server endpoint for removing uploaded files
ChunkSize
chunkSize
0
Chunk size in bytes; enables chunk upload when > 0
RetryCount
retryCount
3
Number of retry attempts on chunk failure
RetryAfterDelay
retryAfterDelay
500
Delay (ms) before chunk retry
属性TagHelper属性类型默认值用途
AllowedExtensions
allowedExtensions
string
""
允许的文件类型(例如:
".jpg,.png"
MaxFileSize
maxFileSize
double
30000000
最大文件大小(字节)
MinFileSize
minFileSize
double
0
最小文件大小(字节)
Multiple
multiple
bool
true
是否允许选择多个文件
AutoUpload
autoUpload
bool
true
文件选择后是否自动上传
SequentialUpload
sequentialUpload
bool
false
是否按顺序上传文件
DropArea
dropArea
stringnull自定义拖放区域的CSS选择器
DirectoryUpload
directoryUpload
bool
false
是否允许选择文件夹/目录
ShowFileList
showFileList
bool
true
是否显示默认文件列表
Template
template
stringnull文件列表项的自定义HTML模板
CssClass
cssClass
string
""
根元素的额外CSS类
EnableRtl
enableRtl
bool
false
是否启用从右到左渲染
Locale
locale
string
""
本地化区域代码
AsyncSettings子属性(通过
<e-uploader-asyncsettings>
设置):
属性TagHelper属性默认值用途
SaveUrl
saveUrl
""
保存上传文件的服务端端点
RemoveUrl
removeUrl
""
移除已上传文件的服务端端点
ChunkSize
chunkSize
0
分片大小(字节);大于0时启用分片上传
RetryCount
retryCount
3
分片上传失败后的重试次数
RetryAfterDelay
retryAfterDelay
500
分片重试前的延迟时间(毫秒)

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组件。