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

如何在ASP.NET Core 6中实现文件上传并返回文件URL

修改代码实现图片本地保存并返回URL

关键修改点

  • 注入IWebHostEnvironment获取Web应用根目录,确保文件保存到静态资源可访问路径
  • 生成唯一文件名防止重复覆盖
  • 将图片保存到wwwroot/images目录(若目录不存在自动创建)
  • 构建可直接访问的图片URL返回至视图

修改后的HomeController代码

namespace img_cleaner.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IWebHostEnvironment _webHostEnvironment;

    public HomeController(ILogger<HomeController> logger, IWebHostEnvironment webHostEnvironment)
    {
        _logger = logger;
        _webHostEnvironment = webHostEnvironment;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

    [HttpPost]
    public async ValueTask<IActionResult> ImageReiceve(ImageUpload imageUpload)
    {
        ArgumentNullException.ThrowIfNull(imageUpload.file);

        // 获取wwwroot下的images目录路径
        string imagesPath = Path.Combine(_webHostEnvironment.WebRootPath, "images");
        // 若目录不存在则创建
        if (!Directory.Exists(imagesPath))
        {
            Directory.CreateDirectory(imagesPath);
        }

        // 生成唯一文件名(Guid + 原文件扩展名)
        string uniqueFileName = $"{Guid.NewGuid()}{Path.GetExtension(imageUpload.file.FileName)}";
        string filePath = Path.Combine(imagesPath, uniqueFileName);

        // 保存文件到本地
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await imageUpload.file.CopyToAsync(stream);
        }

        // 构建图片访问URL
        string imageUrl = $"/images/{uniqueFileName}";

        return View(new ImageResult(){ ImageUrl = imageUrl });
    }
};

对应的ViewModel调整(需确保ImageResult类包含ImageUrl属性)

public class ImageResult
{
    public string ImageUrl { get; set; }
}

Program.cs 无需额外修改

原代码已配置app.UseStaticFiles(),确保wwwroot下的静态资源可被访问,因此图片URL可以直接通过/images/xxx访问。

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios.
    app.UseHsts();
}

app.UseStaticFiles();
app.UseHttpsRedirection();

app.UseRouting();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:20:43