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

如何在ASP.NET Core视图中仅显示刚上传的单个文件

解决方案

1. 修改Controller代码

核心是只返回刚上传的文件模型,而非遍历整个目录的所有文件,同时修复异步文件写入的等待问题:

public async Task<IActionResult> Index(IFormFile formFile)
{
    List<FileModel> files = new List<FileModel>();
    try
    {
        if (formFile != null && formFile.Length > 0)
        {
            string fileName = Path.GetFileName(formFile.FileName);
            string uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Files", fileName);
            
            // 用await确保文件完全写入后再继续
            using (var stream = new FileStream(uploadPath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
            
            ViewBag.Message = "File uploaded successfully.";
            // 仅将刚上传的文件加入模型
            files.Add(new FileModel { FileName = fileName });
        }
    }
    catch
    {
        ViewBag.Message = "Error while uploading the files.";
    }
    
    // 首次加载页面(无上传动作)时返回空列表
    return View(files);
}

2. 视图代码优化(可选)

由于模型现在最多仅包含一个文件,你可以保留原有循环逻辑(只会渲染一行),也可以改成更简洁的判断式渲染:

<table>
    <tr>
        <th>File Name</th>
        <th></th>
    </tr>
    @if (Model.Any())
    {
        <tr>
            <td>@Model.First().FileName</td>
            <td>@Html.ActionLink("Download", "DownloadFile", new { fileName = Model.First().FileName })</td>
        </tr>
    }
    else
    {
        <tr>
            <td colspan="2">No file uploaded yet.</td>
        </tr>
    }
</table>

<!-- 表单部分保留,注意补充action路径指向你的Index方法 -->
<form enctype="multipart/form-data" id="contactForm1" action="/你的控制器名/Index" method="post">
    <a href="javascript:void(0);" class="btn btn-icon fs-xl mr-1" data-toggle="tooltip" data-original-title="Attach files" data-placement="top">
        <div>
            <input type="file" id="choose-file" name="formFile" />
            <label for="choose-file"> <i class="fal fa-paperclip color-fusion-300"></i></label>
        </div>
    </a>
    <button class="btn btn-info shadow-0 ml-auto " id="postimg">Post</button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    var frm = $('#contactForm1');
    frm.submit(function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            enctype: 'multipart/form-data',
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function (data) {
                // 可选优化:局部更新表格,避免整页刷新
                $('#contactForm1').prev('table').replaceWith($(data).find('table'));
                console.log('File uploaded successfully!');
            }
        });
    });
</script>

关键修改说明

  • 移除了Controller中遍历Files目录的逻辑,仅在上传成功时将当前文件加入模型。
  • 修复了CopyToAsync未加await的问题,避免文件未完全写入就返回视图。
  • 视图添加了无文件时的提示,AJAX成功后可局部更新表格,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:05:24