ASP.NET Tutorial/ASP.net Controls/FileUpload — различия между версиями

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

Текущая версия на 12:00, 26 мая 2010

Accepting File Uploads

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">
    <div>
    <asp:Label
        id="lblImageFile"
        Text="Image File:"
        AssociatedControlID="upImage"
        Runat="server" />
    <asp:FileUpload
        id="upImage"
        Runat="server" />
    <br /><br />
    <asp:Button
        id="btnAdd"
        Text="Add Image"
        OnClick="btnAdd_Click"
        Runat="server" />
    <hr />
    <asp:DataList
        id="dlstImages"
        RepeatColumns="3"
        runat="server">
        <ItemTemplate>
        <asp:Image ID="Image1"
            ImageUrl="<%# Eval("Name", "~/UploadImages/{0}") %>"
            style="width:200px"
            Runat="server" />
        <br />
        <%# Eval("Name") %>
        </ItemTemplate>
    </asp:DataList>
    </div>
    </form>
</body>
</html>


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

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


FileUpload Test

<%@ 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">
    <div>
    Choose a file to upload to the server<br />
    <asp:FileUpload ID="fupTest" runat="server" Width="400px"/>
    <br />
    <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>
    </div>
    </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 += "<br/>";
                    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";
        }
    }
}


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

<%@ 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("<h1>The upload path doesn"t exist: {0}</h1>",
                savePath));
            Response.End();
        }
        if (FileUpload1.HasFile)
        {
            string fileName = FileUpload1.FileName;
            savePath += fileName;
            FileUpload1.SaveAs(savePath);
            UploadStatusLabel.Text = "File saved as: <i>" + savePath + "</i>";
        }
        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>
    <div id="pageContent">
        <form id="Form1" runat="server">
          <h4>Select a picture to upload:</h4>
            <b>Upload Path</b><br />
            <asp:textbox id="UploadPath" runat="server" text="c:\temp\pictures\" />
            <hr />
            <b>Picture to upload</b><br />
            <asp:fileupload id="FileUpload1" runat="server" />
            <br /><br />
           
           <asp:button id="UploadButton" 
               text="Upload"
               onclick="UploadButton_Click"
               runat="server">
           </asp:button>  
           
           <hr />
           
           <asp:label id="UploadStatusLabel" runat="server" />
         </form>
    </div>
</body>
</html>


Upload file to server

<%@ 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">
    <div>
    <asp:FileUpload ID="Uploader" runat="server" Height="24px" Width="472px" />&nbsp;
        <asp:Button ID="cmdUpload" runat="server" Height="24px" OnClick="cmdUpload_Click"
            Text="Upload" Width="88px" /><br />
        <br />
        <asp:Label ID="lblInfo" runat="server" EnableViewState="False" Font-Bold="True"></asp:Label></div>
    </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;
            }
        }
    }
}


Uploading files using the new FileUpload control (C#)

<%@ 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 + "<br>" +
                   FileUpload1.PostedFile.ContentLength + " kb<br>" +
                   "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>


Uploading files using the new FileUpload control (VB)

<%@ 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 & "<br>" & _
                   "File Size: " & _
                   FileUpload1.PostedFile.ContentLength & " kb<br>" & _
                   "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>