关于文件的上传问题!

时间:2022-08-29 12:40:14

前台:
<body>
  <form name="form1" method="post" runat="server">
   <div align="center"><BR>
    <span id="Message" runat="server"></span>
    <asp:Label id="Label2" runat="server">图片文件:</asp:Label>
    <INPUT id="File1" type="file" name="File1" runat="server">&nbsp; <input id="Submit1" type="submit" value="上传" name="Submit" runat="server">
    <BR>
    <br>
    <asp:Label id="Label1" runat="server">允许上传的类型:jpg,gif大小限制:1M。</asp:Label>
   </div>
  </form>
 </body>

后台
private void Submit1_ServerClick(object sender, System.EventArgs e)
  {
   string fileextention = Path .GetExtension(File1.PostedFile.FileName);
   string aa = DateTime.Now.ToString().Replace(":","").Replace("-","").Replace(" ","");
   string filename = aa + fileextention;
   string filepath = Server.MapPath("uploadimg/" + filename);

   string filetype = File1.PostedFile.ContentType.ToString();//获取上传文件的类型
   
   if(filetype != "image/pjpeg" && filetype != "image/gif")//判断是不是gif或是jpg图象文件
   {
    Message.InnerHtml = "只允许上传*.gif和*.jpg图片文件!";
    Message.Style["Color"]="red";
    return;
   }
   filepath1 = "...." + filename;
   
   Session["filepath1"] = filepath1;//将上传的图片路径暂时保存

   if(File.Exists(filepath))
   {
    Message.InnerHtml = "上传文件重名,请改名后再上传!";
    Message.Style["Color"] = "red";
    return;
   }
   else
   {
    if(File1.PostedFile != null)
     try
     {
      File1.PostedFile.SaveAs(filepath);
      Message.InnerHtml = "<b>成功上传!</b>";
       
      Label2.Visible = false;
      File1.Visible = false;
      Submit1.Visible = false;
      Label1.Text = "<a href=# onclick=Addpic('"+filepath1+"');><font color=red>点击这里添加到编辑器中</font></a>";
     }
     catch(Exception exc)
     {
      Message.InnerHtml = "保存文件时出错<b>" + filepath + "</b><br>"+ exc.ToString();
     }
   }