我尝试使用asp.net(c#)创建一个应用程序,用户将使用fileupload控件上传单个文件(任何数据格式doc,docx,pdf)。
然后我必须将文件的内容保存在用户选择的数据库中。数据库的结构是:
字段数据类型 id int title nvarchar(MAX) body varbinary(MAX) bodyoverview nvarchar(MAX) 贴出日期
文件内容将保存在body属性中。我还有以下代码:
protected async void Button_Upload_Click(object sender, EventArgs e)
{
StringBuilder stringBuilder = new StringBuilder();
if(FileUpload1.HasFile)
{
try
{
string FileContent = String.Empty;
using(StreamReader inputStreamReader=new StreamReader(FileUpload1.PostedFile.InputStream))
{
FileContent = await inputStreamReader.ReadToEndAsync();
foreach (char c in FileContent.ToCharArray())
{
stringBuilder.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
}
}
SqlConnection sqlConnection = new SqlConnection("Data Source=(localdb)\\ProjectsV12;Initial Catalog=Blog;Integrated Security=True");
string query = "insert into blogthumbnails values(@blogtitle,@body,@bodyoverview,@allowcomments,@commentscount,@postedon)";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlCommand.Parameters.AddWithValue("@blogtitle", TextBox_Title_Of_The_Blog.Text);
sqlCommand.Parameters.AddWithValue("@body", stringBuilder);
sqlCommand.Parameters.AddWithValue("@postedon", DateTime.Now.Date);
await sqlConnection.OpenAsync();
try
{
int i = sqlCommand.ExecuteNonQuery();
if(i>0)
{
Label_File_Upload_Status.Text = "File Uploaded";
}
else
{
Label_File_Upload_Status.Text = "Please try again";
}
}
catch(SqlException sqlException)
{
Label_File_Upload_Status.Text = sqlException.Message.ToString();
}
}
catch(Exception FileUploadException)
{
Label_File_Upload_Status.Text = "Error in uploading file. Please try again. Error: "+FileUploadException.Message;
}
}
else
{
Label_File_Upload_Status.Text = "Please select a file to upload";
}
}
但是我收到了错误。请帮忙。提前致谢
答案 0 :(得分:1)
默认情况下,StringBuilder不是可以映射到NVARCHAR,TEXT,INT,DEC或其他本机sql类型的本机类型。
试试这些:
sqlCommand.Parameters.AddWithValue("@body", stringBuilder.ToString());
答案 1 :(得分:1)
由于body
属于varbinary
类型,因此数据应为二进制格式。您需要先将stringBuilder
的结果转换为字节数组,然后将其保存在表中。
byte[] byteArray = Encoding.UTF8.GetBytes(Convert.ToString(stringBuilder));
sqlCommand.Parameters.AddWithValue("@body", byteArray);
答案 2 :(得分:0)
这一行:sqlCommand.Parameters.AddWithValue("@body", stringBuilder);
应为
sqlCommand.Parameters.AddWithValue("@body", stringBuilder.ToString());