zoukankan      html  css  js  c++  java
  • FileUpload检查上传文件扩展名,限制大小,创建路径存储

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

    <!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>无标题页</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" /> 
    <input id="Button1" runat="server" onserverclick="Button1_ServerClick" type="button"
    value="上传" /></div>
    </form>
    </body>
    </html>

    //Code:
    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;
    using System.IO;

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

    }
    protected void Button1_ServerClick(object sender, EventArgs e)
    {
    //取得字符串:“C:Documents and SettingsAdministratorDesktoppicture213.jpg”
    string fileName = this.FileUpload1.PostedFile.FileName;
    //取得从开始到最后一个“”得长度:fileName.LastIndexOf("\")
    int length = fileName.Length - fileName.LastIndexOf("\") - 1;
    //截取从fileName.LastIndexOf("\") + 1位置到length位置的字符串
    fileName = fileName.Substring(fileName.LastIndexOf("\") + 1, length);
    //取得字符串:“C:Documents and SettingsAdministratorMy DocumentsVisual Studio 2005WebSitesWebSite1upload2”
    string path = Server.MapPath("upload2\");
    //判断有没有path的文件,如果没有则创建一个新的
    if (!Directory.Exists(path))
    {
    Directory.CreateDirectory(path);
    }
    //取得文件的后缀名:“.jpg ”
    string s1 = System.IO.Path.GetExtension(fileName);
    //取得Web.Config中 <appSettings><add key="conn" value="2048"/></appSettings>配置的值
    string s2=System.Configuration.ConfigurationManager.AppSettings["conn"];
    //取得上传的文件的大小,单位为bytes
    int filesize = (FileUpload1.PostedFile.ContentLength) / 1024;
    if (s1 == ".jpg" || s1 == ".gif")
    {
    //如果文件大小<设定大小,则上传文件到:C:Documents and SettingsAdministratorMy DocumentsVisual Studio 2005WebSitesWebSite1upload2213.jpg
    if (filesize < Convert.ToInt32(s2))
    {
    FileUpload1.PostedFile.SaveAs(path + fileName);
    }
    else
    {
    Response.Write("<script>alert('太大了')</script>");
    }
    }
    else
    {
    Response.Write("<script>alert('请选择JPG或GIF格式的文件')</script>");
    }
    }
    }
  • 相关阅读:
    SGU 242. Student's Morning( 网络流 )
    8.23单词
    bzoj1083:繁忙的城市
    求连通分量
    bzoj2761:不重复数字
    bzoj1207:打鼹鼠
    bzoj2748:音量调节
    bzoj1050:旅行comf
    bzoj1996:合唱队
    羞耻羞耻羞耻!!!
  • 原文地址:https://www.cnblogs.com/proving/p/8191940.html
Copyright © 2011-2022 走看看