您可以檢查您的文件名直接它是否包含任何數據或沒有。
像:
if (FileUpload1.FileName != "")
{
FileInfo fi = new FileInfo(FileUpload1.FileName);
byte[] documentContent = FileUpload1.FileBytes;
string name = fi.Name;
string extn = fi.Extension;
// Add Connection string here //
da.InsertCommand.Parameters.Add("@DocumentName", SqlDbType.VarChar).Value = name;
da.InsertCommand.Parameters.Add("@DocumentContent", SqlDbType.VarBinary).Value = documentContent;
da.InsertCommand.Parameters.Add("@DocumentExt", SqlDbType.VarChar).Value = extn;
cs.Open();
da.InsertCommand.ExecuteNonQuery();
cs.Close();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('No Files Uploaded');", true);
}
更新:我認爲在我們的代碼有問題。 U已使用
da.InsertCommand.Parameters.Add("@DocumentName", SqlDbType.VarChar).Value = name;
da.InsertCommand.Parameters.Add("@DocumentContent", SqlDbType.VarBinary).Value = documentContent;
da.InsertCommand.Parameters.Add("@DocumentExt", SqlDbType.VarChar).Value = extn;
來插入數據。所以請嘗試下面的方法來插入數據
if (FileUpload1.FileName != "")
{
FileInfo fi = new FileInfo(FileUpload1.FileName);
byte[] documentContent = FileUpload1.FileBytes;
string name = fi.Name;
string extn = fi.Extension;
SqlConnection connections = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("INSERT INTO tablename(DocumentName, DocumentContent, DocumentExt) VALUES (@DocumentName, @DocumentContent, @DocumentExt)", connections);
SqlParameter param0 = new SqlParameter("@DocumentName", SqlDbType.VarChar);
param0.Value = name;
command.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter("@DocumentContent", SqlDbType.VarBinary);
param1.Value = documentContent;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@DocumentExt", SqlDbType.VarChar);
param2.Value = extn;
command.Parameters.Add(param2);
connections.Open();
int numRowsAffected = command.ExecuteNonQuery();
connections.Close();
if (numRowsAffected != 0)
{
Response.Write("<BR>Rows Inserted successfully");
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('No Files Uploaded');", true);
}
另外考慮一個方面:可能是某人填充選擇文件,但文件是空的。因此請檢查文件長度。 FileUpload1.Content.Length> 0 – Khazratbek