views:

52

answers:

3

Hi everyone!

I'm trying to save in SQL Server DB a file. (It doesn't mutter which type of file) I use for fileContent field with image type that allow NULL. When I executed Command.ExecuteNonQuery() I'm having error-message: "String or binary data would be truncated.\r\nThe statement has been terminated." Below you may see my code:

    CREATE TABLE [NewsContent]
(
         [ID] [int] IDENTITY(1,1) NOT NULL,
         [FileName] [nvarchar](15) NOT NULL,
         [Extension] [nvarchar](5) NOT NULL,
         [Content] [image] NULL
) 


protected void btnUploadFile_Click(object sender, EventArgs e)
{
    if (fileUpload.HasFile)
    {
        try
        {
            Int32 fileLength = fileUpload.PostedFile.ContentLength;
            String fileType = fileUpload.PostedFile.ContentType;
            Stream fileStream = fileUpload.PostedFile.InputStream;
            String fileName = fileUpload.PostedFile.FileName;
            byte[] fileContent = new byte[fileLength];
            fileStream.Read(fileContent, 0, fileLength);
            int status = Utils.DBWorker.UploadFile(fileName, fileType, fileContent);

            if (status == -1)
                StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured";
        }
        catch (Exception ex)
        {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

public static int UploadFile(String fileName, String fileType, byte[] fileContent)
{
    try
    {
        string insertSql = "INSERT INTO [NewsContent] (FileName, Extension, Content) VALUES (@FileName, @Extension, @Content)";
        Command.CommandText = insertSql;
        Command.Parameters.Clear();
        Command.Parameters.Add(new SqlParameter("@FileName", SqlDbType.NVarChar, 100));
        Command.Parameters.Add(new SqlParameter("@Extension", SqlDbType.NVarChar, 50));
        Command.Parameters.Add(new SqlParameter("@Content", SqlDbType.VarBinary));
        Command.Parameters["@FileName"].Value = fileName;
        Command.Parameters["@Extension"].Value = fileType;
        Command.Parameters["@Content"].Value = fileContent;

        return Command.ExecuteNonQuery();
    }
    catch (Exception es)
    {
        return -1;
    }
}

Could someone help me?

A: 

Change following line

Command.Parameters.Add(new SqlParameter("@Content", SqlDbType.VarBinary)); to

Command.Parameters.Add(new SqlParameter("@Content", SqlDbType.Image));

and try once more.

saurabh
The same error-message.
Roman
+1  A: 

Make sure your file name is 15 characters or less and that your extension is 5 characters or less.

Tim S. Van Haren
A: 

Gyes, I've updated definition of table and it works! Thaks for help!

CREATE TABLE [NewsContent]
(
         [ID] [int] IDENTITY(1,1) NOT NULL,
         [FileName] [nvarchar](50) NOT NULL,
         [Extension] [nvarchar](30) NOT NULL,
         [Content] [image] NULL
) 
Roman