在SQL Server中存储文件的问题

时间:2010-10-12 13:46:30

标签: c# asp.net sql-server

我正在尝试在SQL Server DB中保存一个文件。 (它不会嘀咕哪种类型的文件) 我使用fileContent字段,其图像类型允许NULL。 当我执行Command.ExecuteNonQuery()时,我遇到错误消息:“字符串或二进制数据将被截断。\ r \ n语句已被终止。” 您可以在下面看到我的代码:

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

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

确保您的文件名不超过15个字符,并且您的扩展名不超过5个字符。

答案 1 :(得分:0)

是的,我已经更新了表的定义并且它有效! 谢谢你的帮助!

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