You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor Server中连接DevExpress DxUpload控件到SQL Server并使用

在Blazor Server中使用DevExpress DxUpload控件将文件存储到SQL Server

以下是完整的实现步骤,从前端配置到后端数据库存储的全流程:

一、调整前端DxUpload配置

补充你提供的基础代码的缺失逻辑,完善文件选择状态跟踪和API路径生成:

@inject NavigationManager NavigationManager

<label>Upload a file:</label>
<div class="upload-container">
    <div style="@(SelectedFilesCount > 0 ? "display: none" : string.Empty)">
        <span class="drop-file-icon mb-3"></span>
        <span class="mb-3">Click the Select Files button to select a file: </span>
    </div>
    <DxUpload Name="myFile"
        UploadMode="@UploadMode.OnButtonClick"
        AllowMultiFileUpload="true"
        UploadUrl="@GetUploadUrl("api/FileUpload/UploadFiles")"
        SelectedFilesChanged="@SelectedFilesChanged"
        MaxFileSize="15000000"
        CssClass="@(SelectedFilesCount > 0 ? "w-100" : string.Empty)">
        <UploadButtons>
            <DxUploadSelectButton Text="Select Files" />
            <DxUploadSubmitButton Text="Upload" />
        </UploadButtons>
    </DxUpload>
</div>

@code {
    private int SelectedFilesCount { get; set; } = 0;

    private void SelectedFilesChanged(IEnumerable<UploadFileInfo> files)
    {
        SelectedFilesCount = files.Count();
    }

    private string GetUploadUrl(string endpoint)
    {
        return $"{NavigationManager.BaseUri}{endpoint.TrimStart('/')}";
    }
}

二、创建文件上传API控制器

在项目中添加API控制器,接收DxUpload提交的文件并处理存储逻辑:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using YourProjectNamespace.Data;

namespace YourProjectNamespace.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {
        private readonly AppDbContext _dbContext;

        public FileUploadController(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [HttpPost("UploadFiles")]
        public async Task<IActionResult> UploadFiles(List<IFormFile> myFile)
        {
            if (myFile == null || myFile.Count == 0)
                return BadRequest("No files selected.");

            foreach (var file in myFile)
            {
                if (file.Length <= 0) continue;

                using var memoryStream = new MemoryStream();
                await file.CopyToAsync(memoryStream);
                
                var fileEntity = new FileEntity
                {
                    FileName = file.FileName,
                    ContentType = file.ContentType,
                    FileContent = memoryStream.ToArray(),
                    UploadTime = DateTime.UtcNow
                };

                _dbContext.FileEntities.Add(fileEntity);
            }

            await _dbContext.SaveChangesAsync();
            return Ok("Files uploaded successfully.");
        }
    }
}

三、设计SQL Server数据库表

创建用于存储文件的实体类,可通过EF Core迁移生成SQL Server表:

using System.ComponentModel.DataAnnotations;

namespace YourProjectNamespace.Data
{
    public class FileEntity
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [MaxLength(255)]
        public string FileName { get; set; }

        [MaxLength(100)]
        public string ContentType { get; set; }

        [Required]
        public byte[] FileContent { get; set; }

        public DateTime UploadTime { get; set; }
    }

    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

        public DbSet<FileEntity> FileEntities { get; set; }
    }
}

若直接使用SQL语句建表,可执行以下脚本:

CREATE TABLE FileEntities (
    Id INT PRIMARY KEY IDENTITY(1,1),
    FileName NVARCHAR(255) NOT NULL,
    ContentType NVARCHAR(100),
    FileContent VARBINARY(MAX) NOT NULL,
    UploadTime DATETIME NOT NULL
)

四、配置数据库连接与服务

在appsettings.json中添加SQL Server连接字符串:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=YOUR_SERVER_NAME;Database=YOUR_DB_NAME;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}

在Program.cs中注册DbContext并启用API控制器支持:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddControllers();

// 其他配置代码...

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

内容的提问来源于stack exchange,提问作者Timothy Waters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 06:07:03