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

ASP.NET Core MVC实现图片选择并上传至项目Images文件夹

实现图片上传至项目Images文件夹的方案

我正在创建一个网页,页面样式如下:
页面样式

希望将图片选择区域中选中的图片上传到项目的Images文件夹内,现有代码如下,请教如何实现:

现有代码

Index.cshtml

@model IncomeExpenseWeb.Models.IncomeExpenseTable
@{ 
    ViewData["Title"] = "Home Page";
}
<br />
<div class="p-3 mb-2 bg-light text-dark">
    <h2>Add Record</h2>
</div>
@using (Html.BeginForm("Index", "/", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="row">
        <div class="col">
            <div class="mb-3">
                <label for="formGroupExampleInput" class="form-label">Name</label>
                <input type="text" class="form-control" id="Name" placeholder="What is your name?" />
            </div>
        </div>
        <div class="col">
            <div class="mb-3">
                <label for="formGroupExampleInput" class="form-label">Surname</label>
                <input type="text" class="form-control" id="Surname" placeholder="What is your surname?" />
            </div>
        </div>
    </div>
    <div class="form-group">
        <p>Money Status:</p>
        <select class="form-control" id="SelectedId" name="SelectedId">
            <option value="income">Income</option>
            <option value="expense">Expense</option>
        </select>
    </div>
    <br/>
    <div class="form-group">
        <label>Image:</label>
        <input type="file" name="UploadedImage"/>
    </div>
    <br/>
    <div>
        <input type="submit" class="btn btn-success" value="Save">
    </div>
}

Controller

[HttpPost]
public ActionResult Index()
{
    // I didn't know how to write code.
    return View();
}

Model

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;

namespace IncomeExpenseWeb.Models
{
    public partial class IncomeExpenseTable
    {
        public int Id { get; set; }
        public string Name { get; set; } = null!;
        public string Surname { get; set; } = null!;
        public string MoneyStatus { get; set; } = null!;
        // public string Image { get; set; } = null!;
        public IFormFile Image { get; set; } = null!;
    }
}

解决方案

1. 修正视图绑定

确保表单控件与模型属性正确绑定,同时优化文件上传的交互:

  • 给文本框、下拉框添加asp-for标签辅助器,自动完成模型绑定
  • 将文件上传控件的name与模型的Image属性对齐,添加图片类型限制

修改后的Index.cshtml关键部分:

<!-- Name输入框 -->
<input type="text" class="form-control" asp-for="Name" placeholder="What is your name?" />

<!-- Surname输入框 -->
<input type="text" class="form-control" asp-for="Surname" placeholder="What is your surname?" />

<!-- Money Status下拉框 -->
<select class="form-control" asp-for="MoneyStatus">
    <option value="income">Income</option>
    <option value="expense">Expense</option>
</select>

<!-- 图片上传控件 -->
<input type="file" asp-for="Image" accept="image/*"/>

2. 完善控制器的文件上传逻辑

通过依赖注入获取网站根目录路径,处理文件保存逻辑,同时避免文件名重复:

using Microsoft.AspNetCore.Hosting;
using IncomeExpenseWeb.Models;
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    private readonly IWebHostEnvironment _webHostEnvironment;

    public HomeController(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment = webHostEnvironment;
    }

    [HttpPost]
    public async Task<IActionResult> Index(IncomeExpenseTable model)
    {
        if (model.Image != null && model.Image.Length > 0)
        {
            // 构建wwwroot/Images目录路径
            string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "Images");
            // 确保目录存在,不存在则创建
            if (!Directory.Exists(uploadsFolder))
            {
                Directory.CreateDirectory(uploadsFolder);
            }

            // 生成唯一文件名,防止覆盖
            string uniqueFileName = $"{Guid.NewGuid()}_{model.Image.FileName}";
            string filePath = Path.Combine(uploadsFolder, uniqueFileName);

            // 保存文件到目标路径
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await model.Image.CopyToAsync(fileStream);
            }

            // 若需将图片路径存入数据库,可在此设置模型属性(建议模型用string类型存储相对路径)
            // model.ImagePath = $"/Images/{uniqueFileName}";
            // 执行数据库保存操作,如:_context.IncomeExpenseTables.Add(model); await _context.SaveChangesAsync();
        }

        // 上传完成后重定向回首页或列表页
        return RedirectToAction("Index");
    }
}

3. 模型调整(可选)

如果需要持久化图片路径到数据库,建议将模型中的IFormFile Image改为存储路径的字符串属性,因为IFormFile仅用于接收上传文件,不适合数据库存储:

namespace IncomeExpenseWeb.Models
{
    public partial class IncomeExpenseTable
    {
        public int Id { get; set; }
        public string Name { get; set; } = null!;
        public string Surname { get; set; } = null!;
        public string MoneyStatus { get; set; } = null!;
        public string ImagePath { get; set; } = null!; // 存储图片相对路径
    }
}

此时控制器方法需额外添加IFormFile Image参数用于接收上传文件,或在模型中保留临时的IFormFile属性(注意不要映射到数据库)。

4. 静态文件与权限配置

  • 确保项目的wwwroot/Images目录具备读写权限
  • 确认Program.cs中已配置静态文件中间件(默认已添加):
// Program.cs
app.UseStaticFiles();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:03:29