简体   繁体   中英

Saving file base64 string in SQL Server database

I working on a file upload, on upload the file is converted to base64 string and this string is sent to an API that saves the string in a SQL Server database table.

The type of the base64 string column in the table is NVARCHAR(MAX) but I noticed when the file is saved, SQL truncates the string such that when you convert online using base64 to image decoder, it produces just part of the whole picture and I noticed that the base64 string before saving to SQL is about 72,000 in character count but after saving it SQL it is reduced to about 4,000 which is responsible for the incomplete image decoded.

Why does SQL truncate the base64 string and what can I do to help my situation?

Here is my base64 conversion code:

public async Task<IActionResult> UploadFile()
{
    string base64string;
    var myFile = Request.Form.Files["claimFile"];
    var filetype = myFile.ContentType;
    var filepath = Path.GetTempFileName();
    using (var stream = System.IO.File.Create(filepath))
    {
        await myFile.CopyToAsync(stream);
    }
    byte[] imageByte = System.IO.File.ReadAllBytes(filepath);
    base64string = Convert.ToBase64String(imageByte);
    HttpContext.Session.SetString("Base64Str", base64string);
    return new EmptyResult();
}

I suspect the problem might be that, by specifying NVARCHAR (16-byte characters), you're inadvertently "corrupting" the string.

TWO SUGGESTIONS:

  1. Redefine the column as VARCHAR(MAX)

  2. Save a uuencoded string, then read the text back and see if the saved/retrieved string values match.

Look here:

https://dba.stackexchange.com/questions/212160/why-do-i-get-incorrect-characters-when-decoding-a-base64-string-to-nvarchar-in-s

Please post back what you find!

Also - out of curiosity - how are you doing the Base64 encoding in the first place?

i read and write to db but to nText column type with the following just fine: you may convert from vb.net to c# if needed.

#Region "write/read files to db"

Public Function SaveToDB(ByVal fullfilename As String) As String
    Dim filedata = Convert.ToBase64String(File.ReadAllBytes(fullfilename))
    Return filedata
End Function

Public Function LoadFromDB(ByVal filedata As String, ByVal fullfilename As String) As String
    Dim filepath As String = (fullfilename)
    File.WriteAllBytes(filepath, Convert.FromBase64String(filedata))
    Return filepath
End Function

#End Region

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM