教学思路ASP.Net之服务器控件: 四、FileUpload

本文介绍ASP.Net中的文件上传方法,包括单个文件上传、批量上传的实现过程,并演示了如何利用客户端和服务器端验证文件类型及大小。

在ASP.Net中如果想打开一个文件实现保存的效果,不能像Winform中使用openFileDialog控件,可以限制打开文件的类型,是否上传也必须通过另外一个控件的一个事件才能激发,如下Button2_Click.

winform中openFileDialog的使用方法如下,但是可参考性很少

openFileDialog1.Filter = "图片类型(*.jpg)|*.jpg";//限制打开文件的类型
            if (openFileDialog1.ShowDialog() == DialogResult.OK)  //根据对话框的选择结果判断是否上传
            {
                imageList1.Images.Add(Image.FromFile(openFileDialog1.FileName));//上传选中的文件
            }

下面就让我们来学习一下FileUpLoad控件

ContractedBlock.gifExpandedBlockStart.gif单个文件的上传
 1 //上传图片
 2     //TextBox2为上传图片的自定义文件名.
 3     protected void Button2_Click(object sender, EventArgs e)
 4     {
 5         if (FileUpload1.HasFile)//判读是否有文件
 6         {
 7             string filename = FileUpload1.FileName;//得到文件在本地的路径,及全路径
 8             string kzm = filename.Substring(filename.LastIndexOf ("."));//将扩展名存放到变量kzm中
 9             string uploadfilename = Server.MapPath("upload"+"\\"+TextBox2.Text+kzm;//得到文件在服务器上的路径和文件名和扩展名。
10             if (!kzm.Equals(".jpg")&& kzm != ".JPG"//判断扩展名
11                 Response.Write("<script>alert('格式不正确');</script>");
12             if (File.Exists(uploadfilename))         //判断重名
13                 Response.Write("<script>alert('图片重名,请更换图片名称!');</script>");
14             else
15             {
16                 try
17                 {
18                     FileUpload1.SaveAs(uploadfilename);//将文件上传到服务器上。
19                     Image1.ImageUrl = "upload\\" + TextBox2.Text + kzm;//图片路径为刚才上传的文件
20                     Image1.Height = 300;//控制图片的大小
21                     Image1.Width =250;
22                 }
23                 catch(Exception ex)
24                 {
25                      Response .Write ("<script>alert('"+ex.Message.ToString ()+"');</script>");
26                 }
27             }
28         }
29         else
30         {
31             Response.Write("<script>alert('你还没选择上传的图片!');</script>");
32      
33         }
34     }

下面的代码为在客户端书写对于上传控件文本格式的验证方法:

ContractedBlock.gifExpandedBlockStart.gifCode
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upload.aspx.cs" Inherits="Upload" %>

<!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>Asp.net文件上传时的客户端简单验证</title>
    
<script language="javascript" >
function checkmes(id)
{
   var filename 
= document.getElementById(id).value;
   
//验证是否选择文件
   if(filename=="")
   {
     alert(
"请选择一个文件!");
     
return false;
   }
   
   
//验证扩展名
   var ex = filename.substring(filename.length-4);
   
if(ex!=".xls")
   {
      alert(
"你选择的文件类型不正确,请选择一个Excel文件!");
      
return false;
   }
   
   
//最后提示信息
   return confirm("你确定要上传此Excel文件?");
}
</script>

</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<strong>Asp.net文件上传时的客户端简单验证<br />
            
<br />
            
<asp:FileUpload ID="fu_Excel" runat="server" Width="300px" />&nbsp;
            
<asp:Button ID="btn_Upload" runat="server" Text="上 传" OnClick="btn_Upload_Click" />&nbsp;</strong></div>
    
</form>
</body>
</html>

 在CS文件进行调用验证脚本的方法如下:

ContractedBlock.gifExpandedBlockStart.gifCode
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 Upload : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
   {
        btn_Upload.Attributes.Add(
"onclick""javascript:return checkmes('" + fu_Excel.ClientID + "');");
    }

    
protected void btn_Upload_Click(object sender, EventArgs e)
  {
        
//上传文件的服务器端代码
    }
}

 

 对于上传文件的验证方式还可以采用ASP.Net中的验证控件,如下便是对于照片格式的验证方式。

ContractedBlock.gifExpandedBlockStart.gifCode
  <asp:FileUpload ID="FileUpload1" runat="server" />
                                 
<asp:RegularExpressionValidator   
id
="FileUpLoadValidator" runat="server"   
ErrorMessage
="上传图片只能为.jpg或.gif"   
ValidationExpression
="^([a-zA-Z]:\\)[0-9a-zA-Z\u4e00-\u9fa5\w\s\\!@#\$%^&\*\(\)_\+\-=\[\]{};'\,\.]*(.jpg|.JPG|.gif|.GIF|.bmp|.BMP)$"   

ControlToValidate
="FileUpload1"></asp:RegularExpressionValidator>

如果想改变上传文件的大小限制,要在config文件中,在  <system.web/> 节点内加入如下节点及其属性

 <httpRuntime executionTimeout ="90" maxRequestLength="4096"/> 
批量上传:

ContractedBlock.gifExpandedBlockStart.gif批量
 1protected void Button3_Click(object sender, EventArgs e)
 2ExpandedBlockStart.gifContractedBlock.gif    {
 3        HttpFileCollection fileuploadControls = Request.Files;
 4        for (int i = 0; i < fileuploadControls.Count; i++)
 5ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 6            HttpPostedFile fileuploadcontrol = fileuploadControls[i];
 7            if (fileuploadControls[i].ContentLength > 0)
 8ExpandedSubBlockStart.gifContractedSubBlock.gif            {
 9                try
10ExpandedSubBlockStart.gifContractedSubBlock.gif                {
11                    fileuploadcontrol.SaveAs(Server.MapPath("upload"+"\\"+Path.GetFileName( fileuploadControls[i].FileName));
12                }

13                catch (Exception ex)
14ExpandedSubBlockStart.gifContractedSubBlock.gif                {
15                    Response.Write("<script>alert('" + ex.Message.ToString() + "');</script>");
16                }

17            }

18        }

19        Response.Write("<script>alert('上传成功!');</script>");
20    }

21

 

转载于:https://www.cnblogs.com/wangfang224120999/archive/2009/05/31/1398948.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值