WebForm实现文件上传,并预览

实现效果:

页面代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="Button1" runat="server" Text="上传" Width="54px" OnClick="Button1_Click" />
            <asp:Label ID="Label1" runat="server" Text="" Style="color: Red"></asp:Label>
            <asp:Image runat="server" ID="Image1" Style="z-index: 102; left: 20px; position: absolute; top: 49px"
                Width="73px" />
        </div>
    </form>
</body>
</html>

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.FileName == "")
        {
            this.Label1.Text = "上传文件不能为空";
            return;
        }

        bool fileIsValid = false;
        //如果确认了上传文件,则判断文件类型是否符合要求 
        if (this.FileUpload1.HasFile)
        {
            //获取上传文件的后缀 
            String fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();
            String[] restrictExtension = { ".gif", ".jpg", ".bmp", ".png" };
            //判断文件类型是否符合要求 
            for (int i = 0; i < restrictExtension.Length; i++)
            {
                if (fileExtension == restrictExtension[i])
                {
                    fileIsValid = true;
                }
                //如果文件类型符合要求,调用SaveAs方法实现上传,并显示相关信息 
                if (fileIsValid == true)
                {
                    //上传文件是否大于10M
                    if (FileUpload1.PostedFile.ContentLength > (10 * 1024 * 1024))
                    {
                        this.Label1.Text = "上传文件过大";
                        return;
                    }
                    try
                    {
                        //生成的文件放在那个目录下面
                        this.Image1.ImageUrl = "~/File/" +  FileUpload1.FileName;
                        this.FileUpload1.SaveAs(Server.MapPath("~/File/") + FileUpload1.FileName);
                        this.Label1.Text = "文件上传成功!";
                    }
                    catch
                    {
                        this.Label1.Text = "文件上传失败!";
                    }
                    finally
                    {

                    }
                }
                else
                {
                    this.Label1.Text = "只能够上传后缀为.gif,.jpg,.bmp,.png的文件";
                }
            }
        }
    }
}

 

posted @ 2017-05-31 20:42  青年a  阅读(883)  评论(0编辑  收藏  举报