关于.net中的文件的上传
现在遇到一个问题,就是在.net上传文件控件中,要上传只能上传全部文件,不能上传部分文件,下面便是我的代码,希望大家帮忙解决一下
string filepath1 =file1.PostedFile.FileName;
string filepath2 =file2.PostedFile.FileName;
string filepath3 =file3.PostedFile.FileName;
string filename1 = filepath1.Substring(filepath1.LastIndexOf("\\") + 1); string filename2 = filepath2.Substring(filepath2.LastIndexOf("\\") + 1); string filename3 = filepath3.Substring(filepath3.LastIndexOf("\\") + 1);
string serverpath1 = Server.MapPath("System_txt1/") + filename1; string serverpath2 = Server.MapPath("System_txt1/") + filename2; string serverpath3 = Server.MapPath("System_txt1/") + filename3;
file1.PostedFile.SaveAs(serverpath1);
file2.PostedFile.SaveAs(serverpath2);
file3.PostedFile.SaveAs(serverpath3);
string ds2=ConfigurationSettings.AppSettings["System_manage"];
SqlConnection myConnection2=new SqlConnection(ds2);
SqlCommand insertCommand2=new SqlCommand("Insert TextTable value(@file1,@file2,file3)");
insertCommand2.Parameters.Add(new SqlParameter("@txtfile1",SqlDbType.VarChar,200));
insertCommand2.Parameters.Add(new SqlParameter("@txtfile2",SqlDbType.VarChar,200));
insertCommand2.Parameters.Add(new SqlParameter("@txtfile3",SqlDbType.VarChar,200));
insertCommand2.Parameters["@txtfile1"].Value=TextBox1.Text;
insertCommand2.Parameters["@txtfile2"].Value=TextBox2.Text;
insertCommand2.Parameters["@txtfile3"].Value=TextBox3.Text;
insertCommand2.ExecuteNonQuery();
myConnection2.Close();
Response.Write("完成");
上面的代码如果3个file控件使用都会成功,但如果只用两个就会找不到路径
------解决方案--------------------
private void Upload()
{
Boolean fileOK = false;
path = Server.MapPath("~/UploadedImages/");
if (FileUpload1.HasFile)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
string[] allowedExtensions ={ ".gif", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
try
{
FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
Label1.Text = "文件上传成功";
}
catch (Exception ex)
{
Label1.Text = "错误信息:" + ex.Message.ToString();
}
}
else
{
Label1.Text = "文件格式有误,无法上传";
}
}