ASP.NET Tutorial/HTML Controls/File upload

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

input type="file"

   <source lang="csharp">

<script language="C#" runat="server"> protected void PhotoSubmit(object o, EventArgs e) {

   if(thePhoto.PostedFile != null) {
       try {
           string filepath = "C:\\temp\\" + DateTime.Now.Ticks.ToString();
           thePhoto.PostedFile.SaveAs(filepath);
           status.Text = "File saved as " + filepath;
           
       }
       catch (Exception exc) {
           status.Text = "An Error occurred processing the file.  Please try again." + exc.ToString();
       }
   }

} </script> <form runat="server" enctype="multipart/form-data"> Please select an image to submit: <input id="thePhoto" type="file" runat="server">
<input type="button" runat="server" value="Proceed" OnServerClick="PhotoSubmit" /> <asp:label runat="server" id="status" /> </form></source>


PostedFile.SaveAs

   <source lang="csharp">

<%@ Page Language="C#" %> <script runat="server"> void UploadButton_Click(Object sender, EventArgs e) {

   if(FileInput.PostedFile != null)
       {
           try
           {
               FileInput.PostedFile.SaveAs("c:\\test.txt");
           }
           catch (Exception exc)
           {
               Response.Write(exc.Message);
           }
       }
   }

</script> <html>

 <head>
 </head>
 <body>
   <form id="Form1" method="post" enctype="multipart/form-data" runat="server">
       <input id="FileInput" type="file" runat="server" />
       <asp:Button id="UploadButton" onclick="UploadButton_Click" runat="server" Text="Upload"></asp:Button>
   </form>
 </body>

</html></source>


Use the HtmlInputFile control.

   <source lang="csharp">

<%@ Page language="C#"%> <%@ Import Namespace="System.IO" %> <script runat="server">

   void UploadButton_Click(object sender, EventArgs e)
   {
       string savePath = @"c:\";
       if (!Directory.Exists(savePath)) {
string msg = "

The upload path doesn"t exist: {0}

";
           Response.Write(String.Format(msg, savePath));
           Response.End();
       }
       if (FileUpload1.PostedFile != null)
       {
           string fileName = Path.GetFileName(FileUpload1.Value);
           savePath += fileName;
         FileUpload1.PostedFile.SaveAs(savePath);
           UploadStatusLabel.InnerText = "File saved as: " + savePath + "";
       }
       else
       {
           UploadStatusLabel.InnerText = "You did not specify a file to upload.";
       }
   }

</script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">

   <title>HtmlInputFile</title>

</head> <body>

       <form ID="Form1" runat="server">

Select a picture to upload:


           Picture to upload
<input type="file" id="FileUpload1" runat="server" />

<input runat="server" id="UploadButton" type="submit" value="Upload" onserverclick="UploadButton_Click" />

          <span runat="server" id="UploadStatusLabel" />
      </form>

</body> </html></source>