开发者

Problem with storing file in SQL Server

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?


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


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
) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜