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

ASP.NET MVC中Signature Pad签名保存与数据库存储问题求助

ASP.NET MVC集成Signature Pad签名保存问题解决方案

问题核心

当前可正常显示签名画布、执行清空及下载签名操作,但提交表单时无法将签名图片保存至wwwroot/firmas/文件夹,也无法把图片URL存入数据库。以下是针对代码问题的具体修正方案:


前端(Firma.cshtml)修正

1. 调整表单提交配置

  • 表单需显式指定method="post",默认GET方法无法传递较大的base64格式签名数据
  • 绑定表单提交事件,确保签名数据在提交前存入隐藏字段

修改后的表单代码:

<form asp-action="Firma" method="post" onsubmit="return submitForm();">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <input type="hidden" asp-for="IdOt" />

    <div id="signature-pad" class="m-signature-pad">
        <div class="m-signature-pad--body">
            <canvas></canvas>
        </div>
    </div>

    <!-- 其他表单元素保持不变 -->
    
    <button type="submit" id="accept" class="btn btn-info btn-icon-split">
        <span class="icon text-white-50">
            <i class="fas fa-signature"></i>
        </span>
        <span class="text">Firmar</span>
    </button>
    <input type="hidden" id="SignatureDataUrl" asp-for="Firma">
</form>

2. 修正JS提交函数

原函数错误引用了不存在的元素ID,需改为对应隐藏字段的ID:

function submitForm() {
    // 将签名DataURL存入绑定Firma属性的隐藏字段
    document.getElementById('SignatureDataUrl').value = signaturePad.toDataURL();
    return true; // 允许表单正常提交
}

后端(AdminController.cs)修正

1. 注入IWebHostEnvironment获取根路径

在控制器构造函数中注入IWebHostEnvironment,用于获取wwwroot的绝对路径:

private readonly YourDbContext _context;
private readonly IWebHostEnvironment _webHostEnv;

public AdminController(YourDbContext context, IWebHostEnvironment webHostEnv)
{
    _context = context;
    _webHostEnv = webHostEnv;
}

2. 重构POST方法的签名处理逻辑

  • 移除多余的base64png参数,签名数据已通过firmaDTO.Firma传递
  • 生成唯一文件名避免文件覆盖
  • 将图片保存至wwwroot/firmas/,并把相对URL存入数据库

修改后的POST方法代码:

[HttpPost]
public async Task<IActionResult> Firma(FirmaDTO firmaDTO)
{
    if (ModelState.IsValid && !string.IsNullOrEmpty(firmaDTO.Firma))
    {
        var ot = await _context.OrdenTrabajo.FindAsync(firmaDTO.IdOt);
        if (ot == null)
        {
            return NotFound();
        }

        // 解析base64格式的签名数据
        var dataUriParts = firmaDTO.Firma.Split(',');
        if (dataUriParts.Length != 2)
        {
            ModelState.AddModelError("Firma", "签名数据格式错误");
            return View(firmaDTO);
        }

        var encodedImage = dataUriParts[1];
        var decodedImage = Convert.FromBase64String(encodedImage);

        // 生成唯一文件名(结合订单ID和时间戳)
        var fileName = $"signature_{firmaDTO.IdOt}_{DateTime.Now:yyyyMMddHHmmss}.png";
        // 获取wwwroot/firmas的绝对路径
        var savePath = Path.Combine(_webHostEnv.WebRootPath, "firmas", fileName);
        
        // 确保目标目录存在
        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
        // 写入图片文件
        System.IO.File.WriteAllBytes(savePath, decodedImage);

        // 将图片相对URL存入数据库
        ot.Firma = $"/firmas/{fileName}";
        ot.RecibiC = firmaDTO.RecibiC;
        ot.NombreResp = firmaDTO.NombreResp;
        ot.Observaciones = firmaDTO.Observaciones;
        ot.Firmado = true;

        _context.Update(ot);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Exito));
    }

    ViewData["FkCategoria"] = new SelectList(_context.Categoria, "IdCategoria", "NombreCategoria", firmaDTO.FkCategoria);
    ViewData["FkEmpresa"] = new SelectList(_context.Empresa, "IdEmpresa", "NombreEmpresa", firmaDTO.FkEmpresa);
    return View(firmaDTO);
}

额外注意事项

  • 确保应用程序池拥有wwwroot/firmas/目录的写入权限
  • 验证FirmaDTO中的Firma属性为string类型,可接收base64格式字符串
  • 若wwwroot/firmas/目录不存在,代码中已加入自动创建逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:56:29