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

如何使用C#结合ASP.NET Core 5 Web API实现图片上传至服务器或本地文件夹

ASP.NET Core 5 Web API 图片上传实现方案

以下是将图片上传到服务器本地文件夹的完整实现步骤:

1. 基础配置

首先在 Startup.cs 中完成必要配置:

  • 开启静态文件访问,让上传后的图片可以通过HTTP路径直接访问
  • 可按需调整默认上传文件大小限制(默认最大30MB)
    示例配置代码:
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    // 调整上传文件最大大小为50MB,可按需修改
    services.Configure<FormOptions>(options =>
    {
        options.MultipartBodyLengthLimit = 52428800;
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 开启默认wwwroot目录的静态文件访问
    app.UseStaticFiles();
    
    // 如果上传目录不在wwwroot下,需要额外配置静态文件中间件
    // app.UseStaticFiles(new StaticFileOptions
    // {
    //     FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Uploads")),
    //     RequestPath = "/uploads"
    // });
    
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

2. 上传接口实现

创建ApiController编写上传逻辑,核心逻辑包括文件合法性校验、存储路径生成、文件写入、返回访问地址:

[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
    private readonly IWebHostEnvironment _webHostEnv;
    // 允许的图片扩展名
    private readonly List<string> _allowedExts = new() { ".jpg", ".jpeg", ".png", ".gif", ".webp" };
    // 单文件最大大小10MB,可按需修改
    private const long MaxFileSize = 10 * 1024 * 1024;

    public UploadController(IWebHostEnvironment webHostEnv)
    {
        _webHostEnv = webHostEnv;
    }

    [HttpPost("image")]
    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        // 校验文件是否为空
        if (file == null || file.Length == 0)
            return BadRequest("上传文件不能为空");
        
        // 校验文件大小
        if (file.Length > MaxFileSize)
            return BadRequest($"文件大小不能超过{MaxFileSize/1024/1024}MB");
        
        // 校验文件扩展名
        var fileExt = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (string.IsNullOrEmpty(fileExt) || !_allowedExts.Contains(fileExt))
            return BadRequest("仅支持上传jpg/png/gif/webp格式的图片");
        
        // 生成存储目录,按年月日分目录避免单目录文件过多
        var saveDir = Path.Combine(_webHostEnv.WebRootPath, "uploads", DateTime.Now.ToString("yyyyMMdd"));
        if (!Directory.Exists(saveDir))
            Directory.CreateDirectory(saveDir);
        
        // 生成新的文件名,避免同名文件覆盖
        var fileName = $"{Guid.NewGuid():N}{fileExt}";
        var savePath = Path.Combine(saveDir, fileName);
        
        // 写入文件到本地
        await using var stream = new FileStream(savePath, FileMode.Create);
        await file.CopyToAsync(stream);
        
        // 拼接可访问的URL地址
        var accessUrl = $"{Request.Scheme}://{Request.Host}/uploads/{DateTime.Now:yyyyMMdd}/{fileName}";
        
        return Ok(new { url = accessUrl, fileName = fileName, size = file.Length });
    }
}

3. 调用&部署注意事项

  • 前端请求需要设置 Content-Type: multipart/form-data,文件参数名和接口接收的参数名file保持一致
  • 生产环境请给上传目录设置只读权限,禁止脚本执行权限,避免上传恶意脚本被执行
  • 可以根据需求增加图片压缩、水印添加、上传到第三方对象存储服务等扩展逻辑

内容的提问来源于stack exchange,提问作者Charles Darwin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:57:04