首页 > 解决方案 > Docx to byte array not saving in database

问题描述

I'm trying to save .docx files in a database and the code shown here is where I'm converting the .docx file into byte array and then trying to save it into the database.

I'm getting an error

String or binary data would be truncated

I used a column of type varbinary(max) in the database, and the same code is working for pdf and text file but its not working for .docx.

Please guide me.

Controller:

try
{
    byte[] byteDocument = new byte[0];

    if (file.Length > 0)
    {
        long length = file.Length;

        using var fileStream = file.OpenReadStream();
        byteDocument = new byte[length];
        fileStream.Read(byteDocument, 0, (int)file.Length);

        _attachmentDto = new ReviewAttachmentDto
                    {
                        ReviewId = reviewId,                       
                        DocumentType = file.ContentType,
                        Document = byteDocument
                    };
    }

    string requestBody = JsonConvert.SerializeObject(_attachmentDto);

    // Call API
    var _responseObj = await WebAPIHelper.PostDataToAPI(appSettings.SaveUrl, requestBody;
}

Database save:

public void SaveAction(ReviewAttachment reviewAttachment)
{
    Entities.Surveillance.ReviewAttachment reviewAttachmentDB = new Entities.Surveillance.ReviewAttachment();
    reviewAttachmentDB.ReviewId = Int32.Parse(reviewAttachment.ReviewId);
    reviewAttachmentDB.DocumentType = reviewAttachment.DocumentType;
    reviewAttachmentDB.Document = reviewAttachment.Document;

    context.Add(reviewAttachmentDB);
    context.SaveChanges();
}

标签: c#.netasp.net-mvcasp.net-core

解决方案


Since I doubt that your Word doc is over 2 GB in size, then I would suggest that you check to see if you have not reached the size limit for your actual database file. You may need to enable autogrowth on your database. Check the answer here. This person was getting the same error message with a varbinary(max) column.

https://stackoverflow.com/a/11006473/1461269

Also, to find out the implications of enabling this option you can read about it on Microsoft's support site: https://support.microsoft.com/en-ca/help/315512/considerations-for-the-autogrow-and-autoshrink-settings-in-sql-server


推荐阅读