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

ASP.NET Core 6 Blazor上传大图片至SQL Server截断问题求助

解决Blazor上传大图片到SQL Server仅存储64KB的问题

问题根源

直接拼接SQL语句插入超长base64字符串时,部分数据访问组件会默认截断65535字符(64KB)的内容,同时这种写法还存在SQL注入风险。

解决方案

改用参数化查询,让数据库正确识别varchar(max)字段的超长存储能力,同时避免注入风险。

修正后的代码

protected async Task SingleUpload(InputFileChangeEventArgs e)
{
    try
    {
        var file = e.File;

        if (!string.IsNullOrEmpty(file.Name))
        {
            long maxFileSize = 1024L * 1024L * 1024L * 2L;

            await using MemoryStream fs = new MemoryStream();
            await file.OpenReadStream(maxFileSize).CopyToAsync(fs);
            byte[] somBytes = fs.ToArray(); // 直接用MemoryStream的ToArray获取完整字节数组
            string base64String = Convert.ToBase64String(somBytes);

            // 使用参数化查询,避免字符串截断和SQL注入
            string sql = @"INSERT INTO CustomerDocUnAuth (CusDocTypeId, DocFile_64) VALUES(@CusDocTypeId, @DocFile_64)";
            
            // 基于原生SqlCommand的参数化实现,可根据你的数据访问层da调整
            using (SqlCommand cmd = new SqlCommand(sql, yourSqlConnection))
            {
                cmd.Parameters.Add("@CusDocTypeId", SqlDbType.VarChar, 14).Value = id;
                cmd.Parameters.Add("@DocFile_64", SqlDbType.VarChar, -1).Value = base64String; // Size=-1对应varchar(max)
                
                yourSqlConnection.Open();
                int i = cmd.ExecuteNonQuery();
                yourSqlConnection.Close();
            }
        }
    }
    catch (Exception ex)
    {
        // 建议添加异常日志,方便排查问题
        // Logger.LogError(ex, "上传图片失败");
    }
}

额外注意事项

  • 如果你的数据访问层da有封装的参数化插入方法,直接使用该方法传入对应参数即可,核心是不要拼接字符串。
  • 确认原GetBytes方法是否正确返回完整字节数组,若存在问题,直接替换为fs.ToArray()更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:47:48