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

使用ASP.NET结合AngularJs将二进制格式文件/图片上传至SQL Server的咨询

ASP.NET + AngularJS 二进制文件上传到SQL Server实现方案

现有代码问题说明

  • AngularJS原生ng-model不支持<input type="file">控件,无法直接绑定获取文件对象
  • 直接通过JSON格式提交无法传输二进制文件内容,需要使用FormData格式封装请求
  • 后端默认的模型绑定无法直接接收JSON格式传过来的二进制流,需要从请求的文件集合中读取内容转为字节数组存储

前端代码修改

HTML页面调整

给文件选择控件添加onchange事件绑定,实现文件对象读取:

<div class="form-group col-lg-3">
  <div class="profile-images-card">
    <div class="profile-images">
      <img src="../../img/profile1.jpg" id="upload-img" />
    </div>
    <div class="custom-file">
      <label for="fileupload">上传照片</label>
      <input type="file" id="fileupload" onchange="angular.element(this).scope().setFile(this, 'img')" accept="image/*" />
    </div>
  </div>
  <div>
    <label for="formFile" class="form-label">CV</label>
    <input class="form-control" type="file" id="formFile" onchange="angular.element(this).scope().setFile(this, 'CV')" accept=".doc,.docx,.pdf" />
  </div>
  <br /> <br />
  <div style="float:right">
    <input class="btn btn-danger btn-rounded btn-sm" type="button" value="清空" ng-click="clearPersonnel()" />
    <input class="btn btn-primary btn-rounded btn-sm" type="button" id="add" value="保存" ng-click="Add(myform.$valid)" />
  </div>
</div>

AngularJS控制器调整

新增文件读取方法,提交请求改用FormData封装:

// 新增文件读取绑定方法
$scope.setFile = function(element, field) {
    const file = element.files[0];
    $scope.$apply(() => {
        $scope[field] = file;
    });
    // 可选:添加图片预览逻辑
    if (field === 'img') {
        const reader = new FileReader();
        reader.onload = e => {
            document.getElementById('upload-img').src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
};

$scope.Add = function(isValid) {
    if (!isValid) return;
    // 使用FormData封装文件和其他字段
    const formData = new FormData();
    formData.append('Image', $scope.img);
    formData.append('CV', $scope.CV);
    // 如有其他表单字段,也可通过append方法添加,例如:formData.append('EmpName', $scope.empName)

    $http({
        method: 'POST',
        url: '/Home/employeeCreate',
        data: formData,
        // 设为undefined让浏览器自动生成带分隔符的Content-Type
        headers: {'Content-Type': undefined},
        transformRequest: angular.identity
    }).then(res => {
        // 成功提交后的逻辑
    }).catch(err => {
        // 错误处理逻辑
    });
};

后端代码修改

数据模型配置

确保Models.Employee类中存储文件的字段为字节数组类型:

public class Employee
{
    // 其他字段略
    public byte[] Image { get; set; }
    public byte[] CV { get; set; }
    // 可选:新增字段存储文件类型,方便读取时设置响应头
    public string ImageContentType { get; set; }
    public string CVContentType { get; set; }
}

控制器逻辑调整

从请求文件集合中读取内容,转为字节数组后存入模型:

public JsonResult employeeCreate()
{
    try
    {          
        Employee _employee = new Employee();
        // 处理图片文件
        if (Request.Files["Image"] != null && Request.Files["Image"].ContentLength > 0)
        {
            var imgFile = Request.Files["Image"];
            byte[] imgBuffer = new byte[imgFile.ContentLength];
            imgFile.InputStream.Read(imgBuffer, 0, imgFile.ContentLength);
            _employee.Image = imgBuffer;
            _employee.ImageContentType = imgFile.ContentType;
        }
        // 处理CV文件
        if (Request.Files["CV"] != null && Request.Files["CV"].ContentLength > 0)
        {
            var cvFile = Request.Files["CV"];
            byte[] cvBuffer = new byte[cvFile.ContentLength];
            cvFile.InputStream.Read(cvBuffer, 0, cvFile.ContentLength);
            _employee.CV = cvBuffer;
            _employee.CVContentType = cvFile.ContentType;
        }
        // 其他字段赋值,例如:_employee.Name = Request.Form["EmpName"]
        db.Employee.Add(_employee);
        db.SaveChanges();
        return GetEmployee();
    }
    catch (Exception ex)
    {
        return Json(ex.Message);
    }
}

SQL Server字段配置

员工表中存储文件的字段需设置为varbinary(MAX)类型,避免文件大小限制:

ALTER TABLE Employee
ADD Image VARBINARY(MAX) NULL,
    CV VARBINARY(MAX) NULL,
    ImageContentType NVARCHAR(100) NULL,
    CVContentType NVARCHAR(100) NULL

文件读取展示(可选)

如果需要在前端展示存储的图片或下载CV,可新增后端接口返回文件流:

public FileResult GetEmployeeImage(int empId)
{
    var emp = db.Employee.FirstOrDefault(e => e.Id == empId);
    if (emp?.Image == null) return null;
    return File(emp.Image, emp.ImageContentType);
}

public FileResult DownloadEmployeeCV(int empId)
{
    var emp = db.Employee.FirstOrDefault(e => e.Id == empId);
    if (emp?.CV == null) return null;
    return File(emp.CV, emp.CVContentType, "员工简历.pdf");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:39:01