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

.NET Core中IFormFile复制后文件大小为0字节问题求助

解决IFormFile复制到外部文件夹后文件大小为0字节的问题

核心问题在于你没有等待异步文件复制操作完成,就提前关闭了文件流,导致文件内容完全没写入。以下是具体修复方案:

问题根源

代码中_ = file.ImageUpload.CopyToAsync(newFileStream);使用了弃元操作符,没有等待异步复制任务完成就直接执行newFileStream.Close(),此时文件流还没完成写入,最终生成0字节空文件。

修复步骤

  1. 等待异步复制完成:给CopyToAsync添加await关键字,确保文件内容完全写入后再释放流。
  2. 用using自动管理流:using语句会在代码块结束时自动释放FileStream资源,无需手动调用Close(),避免资源泄漏。
  3. 等待API请求完成:ApiPostResponse同样是异步操作,添加await确保数据库数据提交完成后再返回视图。

修改后的控制器代码

[HttpPost]
public async Task<IActionResult> AddImage(Images file)
{
    file.is_deleted = "0";
    DateTime currentDateTime = DateTime.Now;
    string formattedDateTime = currentDateTime.ToString("yyyy-MM-dd");
    file.uploaded_on = formattedDateTime;
    file.uploaded_by = GetUserName();
    file.image_name = file.image_name.Replace(" ", "_");

    if (ModelState.IsValid)
    {
        if (file.ImageUpload != null)
        {
            string imageStorage = GetImageStorage();
            string fileName = Guid.NewGuid().ToString() + "_" + file.image_name + ".png";
            imageStorage += fileName;
            
            // using自动管理文件流生命周期
            using (var newFileStream = new FileStream(imageStorage, FileMode.Create))
            {
                // 等待异步复制完成
                await file.ImageUpload.CopyToAsync(newFileStream);
            }
            
            file.image_path = fileName;
        }
    }

    file.ImageUpload = null;
    // 等待API请求完成
    await kneoHttpClient.ApiPostResponse(ConfigAPI() + "Image/Add/", file);
    file = null;
    return View("Index");
}

额外检查项

  • 确认GetImageStorage()返回的目录路径正确,且应用程序拥有该目录的写入权限,否则会抛出权限异常。
  • 验证Images模型中的ImageUpload属性是IFormFile类型,确保表单文件能正确绑定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:52:21