You need to enable JavaScript to run this app. 在.NET Core MVC中如何使用AngularJS实现文件与数据上传?
优惠活动
大模型
产品
解决方案
定价
更多

在.NET Core MVC中如何使用AngularJS实现文件与数据上传?

现有代码调整点
  • 首先修正input标签的事件属性拼写错误:把nchange改为ng-change
  • AngularJS原生不支持input[type=file]的ng-model绑定,所以ng-model="ch.FileName"不会生效,无需额外配置该属性,直接在change事件中传递文件对象即可
  • 不要使用angular.element(this).scope()这种方式获取作用域,不符合AngularJS最佳实践,直接在对应控制器作用域下定义saveChapter方法,事件可直接写为ng-change="saveChapter($event.target.files)"
完整实现流程

前端AngularJS部分

  • 修正文件选择input代码,示例如下:
<input type="file" id="file" name="myFile" ng-change="saveChapter($event.target.files)" />
  • 在AngularJS控制器中编写上传逻辑,使用FormData同时传递文件和其他业务数据,示例代码:
app.controller('yourController', ['$scope', '$http', function($scope, $http) {
  $scope.saveChapter = function(files) {
    if (files && files.length > 0) {
      let formData = new FormData();
      // 添加选中的文件
      formData.append('myFile', files[0]);
      // 添加其他需要提交的业务数据,比如章节信息
      formData.append('chapterName', $scope.ch.chapterName);
      formData.append('chapterId', $scope.ch.chapterId);
      
      $http.post('/YourController/UploadChapter', formData, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      }).then(function(res) {
        // 上传成功后的处理逻辑
        alert('上传成功');
      }, function(err) {
        // 上传失败处理逻辑
        alert('上传失败,请重试');
      });
    }
  }
}]);

注意:transformRequest: angular.identity和headers: {'Content-Type': undefined}是必填配置,作用是让AngularJS不要修改FormData内容,由浏览器自动生成正确的multipart/form-data请求边界。

后端.NET Core MVC部分

  • 注入IWebHostEnvironment用于获取网站根目录,编写接收上传请求的Action方法,示例代码:
public class YourController : Controller
{
    private readonly IWebHostEnvironment _webHostEnvironment;
    public YourController(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment = webHostEnvironment;
    }

    [HttpPost]
    public IActionResult UploadChapter(IFormFile myFile, string chapterName, int chapterId)
    {
        try
        {
            if (myFile != null && myFile.Length > 0)
            {
                // 自定义文件存储路径,默认存放到wwwroot下的uploads文件夹
                var uploadPath = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                // 生成唯一文件名避免重复覆盖
                var fileName = Guid.NewGuid().ToString() + Path.GetExtension(myFile.FileName);
                var filePath = Path.Combine(uploadPath, fileName);

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

                // 此处可添加业务逻辑,将文件路径、章节信息等数据存入数据库

                return Json(new { success = true, message = "上传成功" });
            }
            return Json(new { success = false, message = "未选择有效文件" });
        }
        catch (Exception ex)
        {
            return Json(new { success = false, message = ex.Message });
        }
    }
}
  • 可根据需求在启动配置中添加上传限制,.NET 6+版本在Program.cs中添加如下配置即可:
builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 10 * 1024 * 1024; // 限制最大上传大小为10MB
});
  • 确认项目的wwwroot文件夹存在,且程序运行身份对该目录有写入权限,避免保存文件时报权限错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 17:24:03