Search code examples
c#sqlsql-serversql-server-2014tobase64string

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();
}

Solution

  • 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?