UI设计师

【转】上传文件代码aspx设置

C# ASPX FileUpload服务器 (2013-02-01 22:23:37)

转载▼

aspx程序代码

<%@ Page Language="C#" CodeFile="fileupload.aspx.cs" Inherits="fileupload" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>FileUpload上传文件示例-Mzwu.com</title>

</head>

<body>

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

    <div>

         <asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传文件" /><br />

        <asp:Label ID="Label1" runat="server" Height="269px" Text="Label" Width="360px"></asp:Label></div>

    </form>

</body>

</html>

aspx.cs:

程序代码

protected void Button1_Click(object sender, EventArgs e)

{

    if (FileUpload1.HasFile)

    {

        try

        {

            FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);

            Label1.Text = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +

                          "文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +

                          "文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +

                          "文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" + 

                          "文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +

                          "保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;

        }

        catch (Exception ex)

        {

            Label1.Text = "发生错误:" + ex.Message.ToString();

        }

    }

    else

    {

        Label1.Text = "没有选择要上传的文件!";

    }

}

1.一次上传多个文件

要一次上传多个文件,我们可以像传单个文件那样对每个文件单独进行处理,除此之外,我们还可以使用HttpFileCollection类捕获从Request对象发送来的所有文件,然后再单独对每个文件进行处理,代码如下:

aspx.cs:

程序代码

protected void Button1_Click(object sender, EventArgs e)

{

    string filepath = Server.MapPath("upload") + "\\";

    HttpFileCollection uploadFiles = Request.Files;

    for (int i = 0; i < uploadFiles.Count; i++)

    {

        HttpPostedFile postedFile = uploadFiles[i];

        try

        {

            if (postedFile.ContentLength > 0)

            {

                Label1.Text += "文件 #" + (i + 1) + ":" + System.IO.Path.GetFileName(postedFile.FileName) + "<br/>";

                postedFile.SaveAs(filepath + System.IO.Path.GetFileName(postedFile.FileName));

            }

        }

        catch (Exception Ex)

        {

            Label1.Text += "发生错误: " + Ex.Message;

        }

    }

}

2.上传文件类型的验证

对上传文件类型的验证既可以在客户端进行,也可以在服务器端进行。客户端可以使用验证控件来进行,不过我们今天主要说说如何在服务器端进行验证。上边cs文件中已经用GetExtension获取了文件的扩展名,只要稍加判断即可实现上传类型的验证:

aspx.cs:

程序代码

protected void Button1_Click(object sender, EventArgs e)

{

    if (FileUpload1.HasFile)

    {

        fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);

        if (fileExt == ".rar" || fileExt == ".zip")

        {

            try

            {

                FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);

                Label1.Text = "客户端路径:" + FileUpload1.PostedFile.FileName + "<br>" +

                              "文件名:" + System.IO.Path.GetFileName(FileUpload1.FileName) + "<br>" +

                              "文件扩展名:" + System.IO.Path.GetExtension(FileUpload1.FileName) + "<br>" +

                              "文件大小:" + FileUpload1.PostedFile.ContentLength + " KB<br>" + 

                              "文件MIME类型:" + FileUpload1.PostedFile.ContentType + "<br>" +

                              "保存路径:" + Server.MapPath("upload") + "\\" + FileUpload1.FileName;

            }

            catch (Exception ex)

            {

                Label1.Text = "发生错误:" + ex.Message.ToString();

            }

        }

        else

        {

            Label1.Text = "只允许上传rar、zip文件!";

        }

    }

    else

    {

        Label1.Text = "没有选择要上传的文件!";

    }

}

需要注意的是,我们不能过分依赖于客户端验证控件和服务器端上述方法的验证,因为用户只需将文件扩展名更改为允许的类型就可以避开上边的验证,这对用户来说并不是件困难的事情。

3.解决文件大小限制

在ASP.NET 2.0中FileUpload默认上传文件最大为4M,不过我们可以在web.cofig中修改相关节点来更改这个默认值,相关节点如下:

程序代码

<system.web>

    <httpRuntime maxRequestLength="40690" executionTimeout="6000" />

</system.web>

maxRequestLength表示可上传文件的最大值,executionTimeout表示ASP.NET关闭前允许发生的上载秒数。

4."multipart/form-data"和Request共存

在ASP程序中一旦使用表单上传文件(form的enctype属性值为multipart/form-data),服务器端就不能再用Request.Form来获取表单的值,这种限制在ASP.NET 2.0中已经不存在了:

aspx.cs:

程序代码

protected void Button1_Click(object sender, EventArgs e)

{

    if (FileUpload1.HasFile)

    {

        try

        {

            FileUpload1.SaveAs(Server.MapPath("upload") + "\\" + FileUpload1.FileName);

            Label1.Text = "上传文件:" + FileUpload1.FileName + "<br>" +

                          "说明:" + Request.Form["TextBox1"];//也可以用"TextBox1.Text"来获取说明

        }

        catch (Exception ex)

        {

            Label1.Text = "发生错误:" + ex.Message.ToString();

        }

    }

    else

    {

        Label1.Text = "没有选择要上传的文件!";

    }

}

<%@ Page Language="C#" CodeFile="FileUp.aspx.cs" Inherits="FileUp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>ASP.NET(C#)实现一次性上传多张图片(多个文件)</title>

    

<script type="text/javascript">

var i=1

function addFile()

{

if (i<8)

    {var str = '<BR> <input type="file" name="File" runat="server" style="width: 200px"/>描述:<input name="text" type="text" style="width: 150px" maxlength="20" />'

    document.getElementByIdx_x_x_x_x('MyFile').insertAdjacentHTML("beforeEnd",str)

    }

else

    {

        alert("您一次最多只能上传8张图片!")

    }

    i++

}

</script>

        

</head>

<body>

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

   <div>

        <table id="Table1" align="center" border="0" cellpadding="1" cellspacing="1" class="table">

            <tr>

                <td align="center">

                    <font color="#0000ff" face="宋体" size="3"><strong>上传图片</strong></font></td>

            </tr>

            <tr>

                <td align="center" style="width: 734px">

                    &nbsp;</td>

            </tr>

            <tr>

                <td align="center" style="width: 734px">

                    <asp:Panel ID="Panel5" runat="server">

                        &nbsp; &nbsp;<table width="100%">

                            <tr>

                                <td align="right" style="width: 100px">

                                </td>

                                <td align="left" style="width: 500px">

                                    说明:点增加图片按钮可一次上传多张图片,可为每张图片写上一句不超过20个字的描述。单张图片大小不大于1024k</td>

                            </tr>

                            <tr>

                                <td align="right" style="width: 100px">

                                    请选择图片:<br />

                                </td>

                                <td align="left" style="width: 500px"><p id="MyFile"><input type="button" value="增加图片(Add)"></p><br />

                                    <input id="File1" type="file" name="File" runat="server" style="width: 245px"/>

                                    描述:<input name="text" type="text" style="width: 150px" maxlength="20" />

                                </td>

                            </tr>

                            <tr>

                                <td align="right" style="width: 100px">

                                </td>

                                <td align="left" style="width: 500px">

                                    <asp:Button ID="btnUpload" runat="server" Text="开始上传" OnClick="btnUpload_Click"  />

                                    </td>

                            </tr>

                            <tr>

                                <td align="right" style="width: 100px">

                                </td>

                                <td align="left" style="width: 500px">

                                    <asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></td>

                            </tr>

                        </table>

                    </asp:Panel>

                    &nbsp;

                </td>

            </tr>

            <tr>

                <td align="center" style="width: 734px">

                    <font face="宋体"></font><font face="宋体">&nbsp;</font>

                </td>

            </tr>

        </table>

    </div>

    </form>

</body>

</html>

+++++++++++++++++++++++++++++++++++++++++++++  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;

using System.IO;

public partial class FileUp : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void btnUpload_Click(object sender, EventArgs e)

    {

        lblMessage.Text = "";

        lblMessage.Visible = false;

        System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

        System.Text.StringBuilder strmsg = new System.Text.StringBuilder("");

        string[] rd = Request.Form[1].Split(',');//获得图片描述的文本框字符串数组,为对应的图片的描述

        //string albumid=ddlAlbum.SelectedValue.Trim();

        int ifile;

        for (ifile = 0; ifile < files.Count; ifile++)

        {

            if (files[ifile].FileName.Length > 0)

            {

                System.Web.HttpPostedFile postedfile = files[ifile];

                if (postedfile.ContentLength / 1024 > 1024)//单个文件不能大于1024k

                {

                    strmsg.Append(Path.GetFileName(postedfile.FileName) + "---不能大于1024k<br>");

                    break;

                }

                string fex = Path.GetExtension(postedfile.FileName);

                if (fex != ".jpg" && fex != ".JPG" && fex != ".gif" && fex != ".GIF")

                {

                    strmsg.Append(Path.GetFileName(postedfile.FileName) + "---图片格式不对,只能是jpg或gif<br>");

                    break;

                }

            }

        }

        if (strmsg.Length <= 0)//说明图片大小和格式都没问题

        {

            //以下为创建图库目录

            string dirpath = Server.MapPath("51aspx");

            if (Directory.Exists(dirpath) == false)

            {

                Directory.CreateDirectory(dirpath);

            }

            Random ro = new Random();

            int name = 1;

            for (int i = 0; i < files.Count; i++)

            {

                System.Web.HttpPostedFile myFile = files[i];

                string FileName = "";

                string FileExtention = "";

                FileName = System.IO.Path.GetFileName(myFile.FileName);

                string stro = ro.Next(100, 100000000).ToString() + name.ToString();//产生一个随机数用于新命名的图片

                string NewName = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;

                if (FileName.Length > 0)//有文件才执行上传操作再保存到数据库

                {

                    FileExtention = System.IO.Path.GetExtension(myFile.FileName);

                    string ppath = dirpath + @"\" + NewName + FileExtention;

                    myFile.SaveAs(ppath);

                }

                name = name + 1;//用来重命名规则的变量

            }

            Response.Write("<script>alert('恭喜,图片上传成功!')</script>");

        }

        else

        {

            lblMessage.Text = strmsg.ToString();

            lblMessage.Visible = true;

        }

    }

}

=================

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
  <title>多文件上传测试</title>

  <script type="text/javascript">
    function addFile() {
      var div = document_createElement_x_x("div");
      var f = document_createElement_x_x("input");
      f.setAttribute("type", "file")
      f.setAttribute("name", "File")
      f.setAttribute("size", "50")
      div.a(f)
      var d = document_createElement_x_x("input");
      d.setAttribute("type", "button")
      d.setAttribute("onclick", "deteFile(this)");
      d.setAttribute("value", "移除")
      div.a(d)
document.getElementByIdx_x_x("_container").a(div);
    }

    function deteFile(o) {
      while (o.tagName != "DIV") o = o.parentNode;
      o.parentNode.removeChild(o);
    }
  </script>

</head>
<body>
  <form id="form1" runat="server" method="post" enctype="multipart/form-data">
  <h3>多文件上传</h3>
   用户名:<asp:TextBoxID="TextBox1" runat="server"></asp:TextBox>
  <div id="_container">
    <input type="file" size="50" name="File"/>
  </div>
  <div>
    <input type="button" value="添加文件(Add)" onclick="addFile()"/>
  </div>
  <div style="padding:10px 0">
    <asp:Buttonrunat="server" Text="开始上传" ID="UploadButton"
      onclick="UploadButton_Click"></asp:Button>
  </div>
  <div>
    <asp:Label ID="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt"
      Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>
  </div>
  </form>
</body>
</html>

C#代码

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

publicpartialclass MultiFileUpload : System.Web.UI.Page
{
    protectedvoid UploadButton_Click(object sender, EventArgs e)
    {
      ///'遍历File表单元素
      HttpFileCollection files = HttpContext.Current.Request.Files;

      /// '状态信息
      System.Text.StringBuilder strMsg = new System.Text.StringBuilder("您输入的用户名是:" + TextBox1.Text +"<br/>");
      strMsg.Append("上传的文件分别是:<hr color='red'/>");
      try
      {
        for (int iFile =0; iFile < files.Count; iFile++)
        {
          ///'检查文件扩展名字
          HttpPostedFile postedFile = files[iFile];
          string fileName, fileExtension;
          fileName = System.IO.Path.GetFileName(postedFile.FileName);
          if (fileName !="")
          {
            fileExtension = System.IO.Path.GetExtension(fileName);
            strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() +"<br>");
            strMsg.Append("客户端文件地址:" + postedFile.FileName +"<br>");
            strMsg.Append("上传文件的文件名:" + fileName +"<br>");
            strMsg.Append("上传文件的扩展名:" + fileExtension +"<br><hr>");
            ///'可根据扩展名字的不同保存到不同的文件夹
            ///注意:可能要修改你的文件夹的匿名写入权限。
            postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName);
          }
        }
        strStatus.Text = strMsg.ToString();
      }
      catch (System.Exception Ex)
      {
        strStatus.Text = Ex.Message;
      }

    }
}

下载

public void Download(string path) //要下载文件的名称 {  比如string path = " \\images\\a.text";自己检查自己的路径问题,有的需要添加上级目录 有的直接输入文件名就可       if (!string.IsNullOrEmpty(path))            {                       string filePath = Server.MapPath("")+path;//路径                  // string filePath =@"C:\Users\Public\Pictures\Sample Pictures\1.jpg";           FileInfo fileInfo = new FileInfo(filePath);                    Response.Clear();                           Response.ClearContent();                      Response.ClearHeaders();                          Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);               Response.AddHeader("Content-Length", fileInfo.Length.ToString());                             Response.AddHeader("Content-Transfer-Encoding", "binary");                           Response.ContentType = "application/octet-stream";                              Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");              Response.WriteFile(fileInfo.FullName);                        Response.Flush();                          Response.End();                    }}============imagelist设置图片,timer获取随机数
picturebox显示图片
  private List<Image> lst= new List<Image>();
  private int ImageIndex = 0;
  private Timer timer1 = new Timer();
  private void Form1_Load(object sender, EventArgs e)
  {
  lst.Add(Image.FromFile(@"C:\1.jpg"));
  lst.Add(Image.FromFile(@"C:\2.gif"));
  lst.Add(Image.FromFile(@"C:\3.gif"));
  timer1.Interval = 1000;
  timer1.Tick += new EventHandler(timer1_Tick);
  timer1.Enabled = true;
    
  }
  void timer1_Tick(object sender, EventArgs e)
  {
  pictureBox1.Image = lst[ImageIndex];
  ImageIndex++;
  if (ImageIndex > lst.Count-1)ImageIndex = 0;
    
  }


评论
回到首页
© UI设计师 | Powered by LOFTER