无法将参数值从String转换为Byte []

时间:2017-12-06 11:36:45

标签: c# asp.net ado.net varbinarymax

网络代码,当我尝试以二进制格式插入字符串时,我遇到了这个问题。

我在decal.DecalLogoFileName和decal.DecalLogoFileName中有二进制格式的图像,所以当我尝试时,

cmd.Parameters.Add(new SqlParameter("@DecalLogoFileName", SqlDbType.Binary)).Value=decal.DecalLogoFileName;

decal.DecalLogoFileName="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUTExIWFhUXGB8aGBcYGR0ZHxobGhoXHRcYGBkaHyghHRolHRcXIjEhJSkrLi4uGB8zODMtNygtLisBCgoKDg0OGhAQGy0lHyUtLS0tLS0tLS0tLS0tLy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSstLS0tLS0tLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAbAAACAwEBAQAAAAAAAAAAAAAEBQIDBgABB//EAEgQAAIBAgQDBQQHBQYDCAMAAAECEQADBBIhMQVBUQYTImFxMoGRoSNCUrHB0fAUcpLS4QczU2KCshVUc0Njg5OiwuLxFiRk/8QAGQEAAwEBAQAAAAAAAAAAAAAAAQIDAAQF/8QALBEAAgICAgECBQQCAwAAAAAAAAECERIhAzFBE2EiMlFxgUKhsdEEkSMzUv/aAAwDAQACEQMRAD8A"

我在贴花中的字符串值为

function readURL(input) {
if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#DecalLogo').attr('src', e.target.result);
            $('#hdImageName').val(e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

这里hdImageName值存储在decal.DecalLogoFileName

我也试过

cmd.Parameters.Add(new SqlParameter("@DecalLogoFileName", SqlDbType.Binary)).Value=Convert.toByte(decal.DecalLogoFileName);

但转换问题即将来临。

DecalLogoFileName的列数据类型设置为varbinary(MAX)

1 个答案:

答案 0 :(得分:0)

试试这个;

var byteArray = Encoding.ASCII.GetBytes(decal.DecalLogoFileName);
cmd.Parameters.Add(new SqlParameter("@DecalLogoFileName", SqlDbType.VarBinary, byteArray.Length)).Value=byteArray;

要从数据库中检索图像,可以使用Encoding.ASCII.GetString(byteArray)将其转换为base64字符串。然后你可以将图像放在img src中;

        <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUTExIWFhUXGB8aGBcYGR0ZHxobGhoXHRcYGBkaHyghHRolHRcXIjEhJSkrLi4uGB8zODMtNygtLisBCgoKDg0OGhAQGy0lHyUtLS0tLS0tLS0tLS0tLy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSstLS0tLS0tLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAbAAACAwEBAQAAAAAAAAAAAAAEBQIDBgABB//EAEgQAAIBAgQDBQQHBQYDCAMAAAECEQADBBIhMQVBUQYTImFxMoGRoSNCUrHB0fAUcpLS4QczU2KCshVUc0Njg5OiwuLxFiRk/8QAGQEAAwEBAQAAAAAAAAAAAAAAAQIDAAQF/8QALBEAAgICAgECBQQCAwAAAAAAAAECERIhAzFBE2EiMlFxgUKhsdEEkSMzUv/aAAwDAQACEQMRAD8A" 
        alt="SampleImage" />