六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 816|回复: 1

使用ASP.NET上传图片汇总

[复制链接]
 楼主| 发表于 2013-12-8 23:34:24 | 显示全部楼层 |阅读模式
1 使用标准HTML来进行图片上传
前台代码:
  1. <body>
  2.     <form id="form1" runat="server">
  3.     <div>
  4.         <table>
  5.             <tr>
  6.                 <td colspan="2" style="height: 21px" >
  7.                     使用标准HTML来进行图片上传</td>
  8.             </tr>
  9.             <tr>
  10.                 <td style="width: 400px">
  11.                     <input id="InputFile" style="width: 399px" type="file" runat="server" /></td>
  12.                 <td style="width: 80px">
  13.                     <asp:Button ID="UploadButton" runat="server" Text="上传图片" OnClick="UploadButton_Click" /></td>
  14.             </tr>
  15.             <tr>
  16.                 <td colspan="2" >
  17.                     <asp:Label ID="Lb_Info" runat="server" ForeColor="Red"></asp:Label></td>                 
  18.             </tr>
  19.         </table>     
  20.     </div>
  21.     </form>
  22. </body>
复制代码
后台代码:
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;

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

  14.     }
  15.     protected void UploadButton_Click(object sender, EventArgs e)
  16.     {
  17.         string uploadName = InputFile.Value;//获取待上传图片的完整路径,包括文件名
  18.         //string uploadName = InputFile.PostedFile.FileName;
  19.         string pictureName = "";//上传后的图片名,以当前时间为文件名,确保文件名没有重复
  20.         if (InputFile.Value != "")
  21.         {
  22.             int idx = uploadName.LastIndexOf(".");
  23.             string suffix = uploadName.Substring(idx);//获得上传的图片的后缀名
  24.             pictureName = DateTime.Now.Ticks.ToString() + suffix;
  25.         }
  26.         try
  27.         {
  28.             if (uploadName != "")
  29.             {
  30.                 string path = Server.MapPath("~/images/");
  31.                 InputFile.PostedFile.SaveAs(path + pictureName);
  32.             }
  33.         }
  34.         catch (Exception ex)
  35.         {
  36.             Response.Write(ex);
  37.         }
  38.     }
  39. }
复制代码

2 单文件上传
        这是最基本的文件上传,在asp.net1.x中没有这个FileUpload控件,只有html的上传控件,那时候要把html控件转化为服务器控件,很不好用。其实所有文件上传的美丽效果都是从这个FileUpload控件衍生,第一个例子虽然简单却是根本。
前台代码:
  1. <body>
  2.     <form id="form1" runat="server">
  3.     <div>
  4.         <table style="width: 90%">
  5.             <tr>
  6.                 <td style="width: 159px" colspan=2>
  7.                     <strong><span style="font-size: 10pt">最简单的单文件上传</span></strong></td>
  8.             </tr>
  9.             <tr>
  10.                 <td style="width: 600px">
  11.                     <asp:FileUpload ID="FileUpload1" runat="server" Width="600px" /></td>
  12.                 <td align=left>
  13.                     <asp:Button ID="FileUpload_Button" runat="server" Text="上传图片" OnClick="FileUpload_Button_Click" /></td>
  14.             </tr>
  15.             <tr>
  16.                 <td colspan=2>
  17.                     <asp:Label ID="Upload_info" runat="server" ForeColor="Red" Width="767px"></asp:Label></td>
  18.             </tr>
  19.         </table>     
  20.     </div>
  21.     </form>
  22. </body>
复制代码
后台代码:
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;

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

  14.     }
  15.     protected void FileUpload_Button_Click(object sender, EventArgs e)
  16.     {
  17.         try
  18.         {
  19.             if (FileUpload1.PostedFile.FileName == "")
  20.             //if (FileUpload1.FileName == "")
  21.             //if (!FileUpload1.HasFile)     //获取一个值,该值指示 System.Web.UI.WebControls.FileUpload 控件是否包含文件。包含文件,则为 true;否则为 false。
  22.             {
  23.                 this.Upload_info.Text = "请选择上传文件!";
  24.             }
  25.             else
  26.             {
  27.                 string filepath = FileUpload1.PostedFile.FileName;  //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
  28.                 //string filepath = FileUpload1.FileName;               //得到上传的文件名20022775_m.jpg
  29.                 string filename = filepath.Substring(filepath.LastIndexOf("\") + 1);//20022775_m.jpg
  30.                 string serverpath = Server.MapPath("~/images/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
  31.                 FileUpload1.PostedFile.SaveAs(serverpath);//将上传的文件另存为
  32.                 this.Upload_info.Text = "上传成功!";
  33.             }
  34.         }
  35.         catch (Exception ex)
  36.         {
  37.             this.Upload_info.Text = "上传发生错误!原因是:" + ex.ToString();
  38.         }
  39.     }
  40. }
复制代码


3 多文件上传

前台代码:
  1. <body>
  2.     <form id="form1" runat="server">
  3.     <div>
  4.     <table style="width: 343px">
  5.             <tr>
  6.                 <td style="width: 100px">
  7.                     多文件上传</td>
  8.                 <td style="width: 100px">
  9.                 </td>
  10.             </tr>
  11.             <tr>
  12.                 <td style="width: 100px">
  13.                     <asp:FileUpload ID="FileUpload1" runat="server" Width="475px" />
  14.                     </td>
  15.                 <td style="width: 100px">
  16.                     </td>
  17.             </tr>
  18.             <tr>
  19.                 <td style="width: 100px">
  20.                     <asp:FileUpload ID="FileUpload2" runat="server" Width="475px" /></td>
  21.                 <td style="width: 100px">
  22.                 </td>
  23.             </tr>
  24.             <tr>
  25.                 <td style="width: 100px">
  26.                     <asp:FileUpload ID="FileUpload3" runat="server" Width="475px" /></td>
  27.                 <td style="width: 100px">
  28.                 </td>
  29.             </tr>
  30.             <tr>
  31.                 <td style="width: 100px">
  32.                     <asp:Button ID="bt_upload" runat="server" OnClick="bt_upload_Click" Text="一起上传" />
  33.                     <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="448px"></asp:Label></td>
  34.                 <td style="width: 100px">
  35.                 </td>
  36.             </tr>
  37.         </table>
  38.     </div>
  39.     </form>
  40. </body>
复制代码
后台代码:
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;

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

  14.     }
  15.     protected void bt_upload_Click(object sender, EventArgs e)
  16.     {
  17.         if (FileUpload1.PostedFile.FileName == "" && FileUpload2.PostedFile.FileName == "" && FileUpload3.PostedFile.FileName == "")
  18.         {
  19.             this.lb_info.Text = "请选择文件!";
  20.         }
  21.         else
  22.         {
  23.             HttpFileCollection myfiles = Request.Files;
  24.             for (int i = 0; i < myfiles.Count; i++)
  25.             {
  26.                 HttpPostedFile mypost = myfiles[i];
  27.                 try
  28.                 {
  29.                     if (mypost.ContentLength > 0)
  30.                     {
  31.                         string filepath = mypost.FileName;//C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
  32.                         string filename = filepath.Substring(filepath.LastIndexOf("\") + 1);//20022775_m.jpg
  33.                         string serverpath = Server.MapPath("~/images/") + filename;//C:\Inetpub\wwwroot\WebSite2\images\20022775_m.jpg
  34.                         mypost.SaveAs(serverpath);
  35.                         this.lb_info.Text = "上传成功!";
  36.                     }
  37.                 }
  38.                 catch (Exception ex)
  39.                 {
  40.                     this.lb_info.Text = "上传发生错误!原因:" + ex.Message.ToString();
  41.                 }
  42.             }
  43.         }
  44.     }
  45. }
复制代码
  

4 客户端检查上传文件类型(以上传图片为例)
  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head runat="server">
  5.     <title>客户端检查上传文件类型</title>
  6.     <script language="javascript">
  7.     function Check_FileType()
  8.     {
  9.         var str=document.getElementById("FileUpload1").value;
  10.         var pos=str.lastIndexOf(".");
  11.         var lastname=str.substring(pos,str.length);
  12.         if(lastname.toLowerCase()!=".jpg"&&lastname.toLowerCase()!=".gif")
  13.         {
  14.             alert("您上传的文件类型为"+lastname+",图片必须为.jpg,.gif类型");
  15.             return false;
  16.         }
  17.         else
  18.         {
  19.             return true;
  20.         }         
  21.     }
  22.     </script>
  23. </head>
  24. <body>
  25.     <form id="form1" runat="server">
  26.     <div>
  27.         <table>
  28.             <tr>
  29.                 <td colspan="2">
  30.                     客户端检查上传文件类型</td>                 
  31.             </tr>
  32.             <tr>
  33.                 <td style="width: 444px">
  34.                     <asp:FileUpload ID="FileUpload1" runat="server" Width="432px" /></td>
  35.                 <td style="width: 80px">
  36.                     <asp:Button ID="bt_upload" runat="server" Text="上传图片" OnClick="bt_upload_Click" OnClientClick="return Check_FileType()" /></td>
  37.             </tr>
  38.             <tr>
  39.                 <td colspan="2" style="height: 21px">
  40.                     <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="515px"></asp:Label></td>                 
  41.             </tr>
  42.         </table>     
  43.     </div>
  44.     </form>
  45. </body>
  46. </html>
复制代码
注意:点击上传时先触发客户端事件OnClientClick="return Check_FileType()"
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;

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

  14.     }

  15.     protected void bt_upload_Click(object sender, EventArgs e)
  16.     {
  17.         try
  18.         {
  19.             if (FileUpload1.PostedFile.FileName == "")
  20.             {
  21.                 this.lb_info.Text = "请选择文件!";
  22.             }
  23.             else
  24.             {
  25.                 string filepath = FileUpload1.PostedFile.FileName;
  26.                 //if (!IsAllowedExtension(FileUpload1))
  27.                 //{
  28.                 //    this.lb_info.Text = "上传文件格式不正确!";
  29.                 //}
  30.                 if (IsAllowedExtension(FileUpload1) == true)
  31.                 {
  32.                     string filename = filepath.Substring(filepath.LastIndexOf("\") + 1);
  33.                     string serverpath = Server.MapPath("~/images/") + filename;
  34.                     FileUpload1.PostedFile.SaveAs(serverpath);
  35.                     this.lb_info.Text = "上传成功!";
  36.                 }
  37.                 else
  38.                 {
  39.                     this.lb_info.Text = "请上传图片!";
  40.                 }
  41.             }
  42.         }
  43.         catch (Exception ex)
  44.         {
  45.             this.lb_info.Text = "上传发生错误!原因:" + ex.ToString();
  46.         }
  47.     }
  48.     private static bool IsAllowedExtension(FileUpload upfile)
  49.     {
  50.         string strOldFilePath = "";
  51.         string strExtension="";
  52.         string[] arrExtension ={ ".gif", ".jpg", ".bmp", ".png" };
  53.         if (upfile.PostedFile.FileName != string.Empty)
  54.         {
  55.             strOldFilePath = upfile.PostedFile.FileName;//获得文件的完整路径名
  56.             strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//获得文件的扩展名,如:.jpg
  57.             for (int i = 0; i < arrExtension.Length; i++)
  58.             {
  59.                 if (strExtension.Equals(arrExtension[i]))
  60.                 {
  61.                     return true;
  62.                 }
  63.             }
  64.         }
  65.         return false;
  66.     }
  67. }
复制代码
注意:若去掉客户端的脚本和客户端事件OnClientClick="return Check_FileType()",在后台代码
改为:
  1. if (!IsAllowedExtension(FileUpload1))
  2.                 {
  3.                     this.lb_info.Text = "上传文件格式不正确!";
  4.                 }
  5. else if (IsAllowedExtension(FileUpload1) == true)
复制代码
即变成服务器端检查上传文件类型。5  服务器端检查上传文件的类型(文件内部真正的格式)
  1. <body>
  2.     <form id="form1" runat="server">
  3.     <div>
  4.         <table>
  5.             <tr>
  6.                 <td colspan="2">
  7.                     服务器检查上传文件类型</td>                 
  8.             </tr>
  9.             <tr>
  10.                 <td style="width: 444px">
  11.                     <asp:FileUpload ID="FileUpload1" runat="server" Width="432px" /></td>
  12.                 <td style="width: 80px">
  13.                     <asp:Button ID="bt_upload" runat="server" Text="上传图片" OnClick="bt_upload_Click" /></td>
  14.             </tr>
  15.             <tr>
  16.                 <td colspan="2" style="height: 21px">
  17.                     <asp:Label ID="lb_info" runat="server" ForeColor="Red" Width="515px"></asp:Label></td>                 
  18.             </tr>
  19.         </table>     
  20.     </div>
  21.     </form>
  22. </body>
复制代码
后台代码:
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;
  10. using System.IO;

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

  15.     }
  16.     protected void bt_upload_Click(object sender, EventArgs e)
  17.     {
  18.         try
  19.         {
  20.             if (FileUpload1.PostedFile.FileName == "")
  21.             {
  22.                 this.lb_info.Text = "请选择文件!";
  23.             }
  24.             else
  25.             {
  26.                 string filepath = FileUpload1.PostedFile.FileName;
  27.                 if (IsAllowedExtension(FileUpload1) == true)
  28.                 {
  29.                     string filename = filepath.Substring(filepath.LastIndexOf("\") + 1);
  30.                     string serverpath = Server.MapPath("images/") + filename;
  31.                     FileUpload1.PostedFile.SaveAs(serverpath);
  32.                     this.lb_info.Text = "上传成功!";
  33.                 }
  34.                 else
  35.                 {
  36.                     this.lb_info.Text = "请上传图片";
  37.                 }
  38.             }
  39.         }
  40.         catch (Exception error)
  41.         {
  42.             this.lb_info.Text = "上传发生错误!原因:" + error.ToString();
  43.         }
  44.     }
  45.     private static bool IsAllowedExtension(FileUpload upfile)
  46.     {
  47.         FileStream fs = new FileStream(upfile.PostedFile.FileName, FileMode.Open, FileAccess.Read);
  48.         BinaryReader r = new BinaryReader(fs);
  49.         string fileclass = "";
  50.         byte buffer;
  51.         try
  52.         {
  53.             buffer = r.ReadByte();
  54.             fileclass = buffer.ToString();
  55.             buffer = r.ReadByte();
  56.             fileclass += buffer.ToString();
  57.         }
  58.         catch
  59.         {  
  60.             
  61.         }
  62.         r.Close();
  63.         fs.Close();
  64.         if (fileclass == "255216" || fileclass == "7173"||fileclass=="6677"||fileclass=="13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
  65.         {
  66.             return true;
  67.         }
  68.         else
  69.         {
  70.             return false;
  71.         }
  72.     }
  73. }
复制代码
转自: http://blog.csdn.net/qing0991/archive/2008/09/06/2890654.aspx







该会员没有填写今日想说内容.

升级  79.33%

0

主题

0

主题

0

主题

举人

Rank: 3Rank: 3

积分
438
发表于 2014-2-21 00:41:20 | 显示全部楼层
不错不错,值得学习啊!












国标15V7A电源适配器 CCC认证
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表