ASP.NET Tutorial/ASP.net Controls/FileUpload

Материал из .Net Framework эксперт
Версия от 15:00, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Accepting File Uploads

   <source lang="csharp">

Important properties, events Enabled: disable the FileUpload control. FileBytes: get the uploaded file as a byte array. FileContent: get the uploaded file as a stream. FileName: get the name of the file uploaded. HasFile: Returns True when a file has been uploaded. PostedFile: get the uploaded file wrapped in the HttpPostedFile object. Focus: set the form focus to the FileUpload control. SaveAs: save the uploaded file to the file system. <%@ Page Language="C#" %> <%@ Import Namespace="System.IO" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">

   protected void btnAdd_Click(object sender, EventArgs e)
   {
       if (upImage.HasFile)
       {
           if (CheckFileType(upImage.FileName))
           {
               String filePath = "~/UploadImages/" + upImage.FileName;
               upImage.SaveAs(MapPath(filePath));
           }
       }
   }
   bool CheckFileType(string fileName)
   {
       string ext = Path.GetExtension(fileName);
       switch (ext.ToLower())
       {
           case ".png":
               return true;
           case ".jpg":
               return true;
           default:
               return false;
       }
   }
   void Page_PreRender()
   {
       string upFolder = MapPath("~/UploadImages/");
       DirectoryInfo dir = new DirectoryInfo(upFolder);
       dlstImages.DataSource = dir.GetFiles();
       dlstImages.DataBind();
   }

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

   <title>FileUpload File</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Label
       id="lblImageFile"
       Text="Image File:"
       AssociatedControlID="upImage"
       Runat="server" />
   <asp:FileUpload
       id="upImage"
       Runat="server" />
   

<asp:Button id="btnAdd" Text="Add Image" OnClick="btnAdd_Click" Runat="server" />

   <asp:DataList
       id="dlstImages"
       RepeatColumns="3"
       runat="server">
       <ItemTemplate>
       <asp:Image ID="Image1"
           ImageUrl="<%# Eval("Name", "~/UploadImages/{0}") %>"
           style="width:200px"
           Runat="server" />
       
<%# Eval("Name") %> </ItemTemplate> </asp:DataList>
   </form>

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


Changing the file-size limitation setting in the web.config file

   <source lang="csharp">

<httpRuntime

 idleTime="15"
 executionTimeout="90"
 maxRequestLength="4096"
 useFullyQualifiedRedirectUrl="False"
 minFreeThreads="8"
 minLocalRequestFreeThreads="4"
 appRequestQueueLimit="100"

/></source>


FileUpload Test

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="FileUploadTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>FileUpload Control Test</title>

</head> <body>

   <form id="form1" runat="server">
   Choose a file to upload to the server
<asp:FileUpload ID="fupTest" runat="server" Width="400px"/>
<asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" /> <asp:Label ID="labMessage" runat="server"></asp:Label> <asp:Label ID="labInfo" runat="server"></asp:Label>
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class FileUploadTest : System.Web.UI.Page {

   protected void btnUpload_Click(object sender, EventArgs e)
   {
       try
       {
           if (fupTest.HasFile)
           {
               string path = @"C:\temp\";
               string fullname = path + fupTest.FileName;
               if (System.IO.File.Exists(fullname))
               {
                   labMessage.Text = "File already exists - uploaded cancelled";
               }
               else
               {
                   fupTest.SaveAs(fullname);
                   labMessage.Text = "File successfully uploaded";
                   int contentLength = fupTest.PostedFile.ContentLength;
                   string contentType = fupTest.PostedFile.ContentType;
                   labInfo.Text = "Content Type = " + contentType;
                   labInfo.Text += "
"; labInfo.Text += " Content Length = " + contentLength; byte[] input = new byte[contentLength]; input = fupTest.FileBytes; System.IO.Stream myStream = fupTest.FileContent; int index = 0; while (index < myStream.Length) { byte aByte = (byte)myStream.ReadByte(); index++; } } } else { labMessage.Text = "File was not specified"; } } catch { labMessage.Text = "File was not uploaded"; } }

}</source>


The user selects a file from the local disk and the page manages to persist it to a server location

   <source lang="csharp">

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

   void UploadButton_Click(object sender, EventArgs e)
   {
       string savePath = UploadPath.Text.ToLower();
       if (!Directory.Exists(savePath))
       {
Response.Write(String.Format("

The upload path doesn"t exist: {0}

",
               savePath));
           Response.End();
       }
       if (FileUpload1.HasFile)
       {
           string fileName = FileUpload1.FileName;
           savePath += fileName;
           FileUpload1.SaveAs(savePath);
           UploadStatusLabel.Text = "File saved as: " + savePath + "";
       }
       else
       {
           UploadStatusLabel.Text = "You did not specify a file to upload.";
       }
   }

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

   <title>File Upload</title>

</head> <body>

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

Select a picture to upload:

           Upload Path
<asp:textbox id="UploadPath" runat="server" text="c:\temp\pictures\" />

           Picture to upload
<asp:fileupload id="FileUpload1" runat="server" />

<asp:button id="UploadButton" text="Upload" onclick="UploadButton_Click" runat="server"> </asp:button>

          <asp:label id="UploadStatusLabel" runat="server" />
        </form>

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


Upload file to server

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UploadFile" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:FileUpload ID="Uploader" runat="server" Height="24px" Width="472px" /> 
       <asp:Button ID="cmdUpload" runat="server" Height="24px" OnClick="cmdUpload_Click"
           Text="Upload" Width="88px" />

<asp:Label ID="lblInfo" runat="server" EnableViewState="False" Font-Bold="True"></asp:Label>
   </form>

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; public partial class UploadFile : System.Web.UI.Page {

   private string uploadDirectory;
   protected void Page_Load(object sender, EventArgs e)
   {
       uploadDirectory = Path.rubine(Request.PhysicalApplicationPath, "Uploads");
   }
   
   protected void cmdUpload_Click(object sender, EventArgs e)
   {
       if (Uploader.PostedFile.FileName == "")
       {
           lblInfo.Text = "No file specified.";
       }
       else
       {
           string extension = Path.GetExtension(Uploader.PostedFile.FileName);
           switch (extension.ToLower())
           {
               case ".png":
               case ".jpg":
                   break;
               default:
                   lblInfo.Text = "This file type is not allowed.";
                   return;
           }
           string serverFileName = Path.GetFileName(Uploader.PostedFile.FileName);
           string fullUploadPath = Path.rubine(uploadDirectory,serverFileName);
           try
           {
               Uploader.PostedFile.SaveAs(fullUploadPath);
               lblInfo.Text = "File " + serverFileName;
               lblInfo.Text += " uploaded successfully to ";
               lblInfo.Text += fullUploadPath;
           }
           catch (Exception err)
           {
               lblInfo.Text = err.Message;
           }
       }
   }

}</source>


Uploading files using the new FileUpload control (C#)

   <source lang="csharp">

<%@ Page Language="C#"%> <script runat="server">

   protected void Button1_Click(object sender, EventArgs e)
   {
       if (FileUpload1.HasFile)
          try {
             FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
             Label1.Text = "File name: " +
                  FileUpload1.PostedFile.FileName + "
" + FileUpload1.PostedFile.ContentLength + " kb
" + "Content type: " + FileUpload1.PostedFile.ContentType; } catch (Exception ex) { Label1.Text = "ERROR: " + ex.Message.ToString(); } else { Label1.Text = "You have not specified a file."; } }

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

   <title>FileUpload Server Control</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:FileUpload ID="FileUpload1" Runat="server" />
       
       <asp:Button ID="Button1" Runat="server" Text="Upload" 
        OnClick="Button1_Click" />
       
       <asp:Label ID="Label1" Runat="server"></asp:Label>
   </form>

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


Uploading files using the new FileUpload control (VB)

   <source lang="csharp">

<%@ Page Language="VB"%> <script runat="server">

  Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
       If FileUpload1.HasFile Then
           Try
               FileUpload1.SaveAs("C:\Uploads\" & _
                  FileUpload1.FileName)
               Label1.Text = "File name: " & _
                  FileUpload1.PostedFile.FileName & "
" & _ "File Size: " & _ FileUpload1.PostedFile.ContentLength & " kb
" & _ "Content type: " & _ FileUpload1.PostedFile.ContentType Catch ex As Exception Label1.Text = "ERROR: " & ex.Message.ToString() End Try Else Label1.Text = "You have not specified a file." End If End Sub

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

   <title>FileUpload Server Control</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:FileUpload ID="FileUpload1" Runat="server" />
       
       <asp:Button ID="Button1" Runat="server" Text="Upload" 
        OnClick="Button1_Click" />
       
       <asp:Label ID="Label1" Runat="server"></asp:Label>
   </form>

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