ASP.NET File Upload 方法

 
ASP.NET File Upload 方法
 

   WebForm7.aspx
 
   <asp:FileUpload ID="FileUpload1" runat="server" />
   <asp:Button ID="Button2" runat="server" Text="Upload" onclick="Button2_Click" />
   <asp:Label ID="Label2" runat="server" Text="" />
 
   <asp:PlaceHolder ID="PlaceHolder1" runat="server" />
 

 

   WebForm7.aspx.cs
 
   protected void Button2_Click(object sender, EventArgs e)
   {
      if (FileUpload1.HasFile)
      {
         try
         {
            string filename;
            if (FileUpload1.PostedFile.ContentType == "image/jpeg")
            {
               filename = FileUpload1.FileName.Trim();
               FileUpload1.SaveAs(Server.MapPath("~/upload_jpg/") + filename);
               Label2.Text = "Upload status: File uploaded!";
               CreatePic(filename, "~/upload_jpg/");
            }
            else if (FileUpload1.PostedFile.ContentType == "image/png")
            {
               filename = FileUpload1.FileName.Trim();
               FileUpload1.SaveAs(Server.MapPath("~/upload_png/") + filename);
               Label2.Text = "Upload status: File uploaded!";
               CreatePic(filename, "~/upload_png/");
            }
            else if (FileUpload1.PostedFile.ContentType == "application/pdf")
            {
               filename = FileUpload1.FileName.Trim();
               FileUpload1.SaveAs(Server.MapPath("~/upload_pdf/") + filename);
               Label2.Text = "Upload status: File uploaded!";
            }
            else if (FileUpload1.PostedFile.ContentType == "application/msword" || FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
            {
               filename = FileUpload1.FileName.Trim();
               FileUpload1.SaveAs(Server.MapPath("~/upload_doc/") + filename);
               Label2.Text = "Upload status: File uploaded!";
            }
            else if (FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel" || FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
               filename = FileUpload1.FileName.Trim();
               FileUpload1.SaveAs(Server.MapPath("~/upload_xls/") + filename);
               Label2.Text = "Upload status: File uploaded!";
            }
            else
            {
               Label2.Text = "Upload status: File Type Incorrected!";
            }
         }
         catch (Exception ex)
         {
            Label2.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
         }
      }
   }
 
   private void CreatePic(String FileName, String Path)
   {
      Image im = new Image();
      im.ImageUrl = Path.Trim() + FileName.Trim();
      PlaceHolder1.Controls.Add(im);
   }