c#多图片上传并生成缩略图的实例代码

所属分类: 网络编程 / ASP.NET 阅读数: 2032
收藏 0 赞 0 分享

前台代码:

复制代码 代码如下:


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

 <!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>
     <style type="text/css">
         li
         {
             list-style: none;
             padding-top: 10px;
         }
     </style>
     <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
     <script type="text/javascript">
         function ValidImage(id, msg) {
             $(id).parent().append("<span>" + msg + "</span>");
             return false;
         }
     </script>
 </head>
 <body>
     <form id="form1" runat="server" enctype="multipart/form-data" method="post">
         <div>
                       <ul>
                 <li>
                     <input type="file" id="upload1" name="upload" />
                 </li>
                 <li>
                     <input type="file" id="upload2" name="upload" />
                 </li>
                 <li>
                     <input type="file" id="upload3" name="upload" />
                 </li>
                 <li>
                     <input type="file" id="upload4" name="upload" /></li>
                 <li>
                     <input type="file" id="upload5" name="upload" />

                 </li>
                 <li>
                     <input type="submit" id="btnPostFile" runat="server" onserverclick="btnPostFile_ServerClick" value="开始上传" />
                 </li>
             </ul>
         </div>
     </form>
 </body>
 </html>

前台就是几个控件和一个ValidImage方法。

后台代码:

复制代码 代码如下:


  protected void btnPostFile_ServerClick(object sender, EventArgs e)
     {
         string filePath = Server.MapPath("/uploadImg");
         const int size = 5242880;
         if (!Directory.Exists(filePath))
         {
             Directory.CreateDirectory(filePath);
         }
         if (Request.Files.Count > 0)
         {
             for (int i = 0; i < Request.Files.Count; i++)
             {
                 HttpPostedFile postFile = Request.Files[i];
                 string uploadFileID = string.Format("#upload{0}", i + 1);  //当前的上传控件ID,因为jquery要调用就加了#
                 string msg = null;                 //提示信息
                 if (postFile.FileName.Trim().Length <= 0)
                 {
                     continue;
                 }
                 if (postFile.ContentLength > size)
                 {
                     msg = "文件太大";
                     Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);//将提示信息发送到客户端
                     continue;
                 }
                 string savePath = Path.Combine(filePath, postFile.FileName);        //图片的保存地址
                 if (!File.Exists(savePath))
                 {
                     postFile.SaveAs(Path.Combine(filePath, postFile.FileName));     //如果文件不存在就保存
                 }
                 else
                 {
                     msg = "文件" + postFile.FileName + "已经存在";
                     Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);//将提示信息发送到客户端
                     continue;
                 }
                 if (IsImg(savePath))            //通过IsImg方法验证文件是否是图片,或者格式是否正确
                 {
                     SmallImg(postFile.InputStream, postFile.FileName);
                 }
                 else
                 {
                     msg = "只能上传JGP、PNG类型的图片,请检查文件格式是否正确";
                     Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);//将提示信息发送到客户端
                     File.Delete(savePath);  //如果不是图片就删除
                 }
             }
         }
     }

复制代码 代码如下:

  #region 验证上传文件的格式
     /// <summary>
     /// 验证上传文件是否是图片
     /// </summary>
     /// <param name="FilePath">文件的保存路径</param>
     /// <returns></returns>
     private bool IsImg(string FilePath)
     {
         using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
         {
             bool result = false;
             BinaryReader br = new BinaryReader(fs, System.Text.Encoding.UTF8);
             string strImg = "";
             byte buffer;
             try
             {
                 buffer = br.ReadByte();
                 strImg = buffer.ToString();
                 buffer = br.ReadByte();
                 strImg += buffer.ToString();
             }
             catch
             {
                 fs.Close();
                 br.Close();

             }
             if (strImg == "255216" || strImg == "13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
             {
                 result = true;
             }
             return result;
         }
     }
     #endregion

复制代码 代码如下:


   #region 将图片生成缩略图
     /// <summary>
     /// 生成缩略图
     /// </summary>
     private void SmallImg(Stream oStream, string FileName)
     {
         using (System.Drawing.Image img = System.Drawing.Image.FromStream(oStream))
         {
             int newWidth = 100;
             int newHeight = 80;
             int oldWidth = img.Width;
             int oldHeight = img.Height;
             if (oldWidth > oldHeight)
             {
                 newHeight = (int)Math.Floor((double)oldHeight * (double)newWidth / (double)oldWidth);
             }
             else
             {
                 newWidth = (int)Math.Floor((double)oldWidth * (double)newHeight / (double)oldHeight);
             }
             using (Bitmap bmp = new Bitmap(newWidth, newHeight))
             {
                 using (Graphics g = Graphics.FromImage(bmp))
                 {
                     g.Clear(Color.Transparent);
                     g.InterpolationMode = InterpolationMode.High;
                     g.CompositingQuality = CompositingQuality.HighQuality;
                     g.SmoothingMode = SmoothingMode.HighQuality;
                     g.DrawImage(img, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, oldWidth, oldHeight), GraphicsUnit.Pixel);
                     string newFileName = Path.GetFileNameWithoutExtension(FileName) + "_small" + Path.GetExtension(FileName);   //缩略图名称
                     string filePath = Server.MapPath("/uploadImg/") + newFileName;
                     bmp.Save(filePath);
                 }
             }

         }
     }
     #endregion

代码有很多需要改进的地方,希望大家多多指点。

更多精彩内容其他人还在看

asp.net 页面间传值与跳转的区别

通过Server.Transfer("b.aspx") 与Response.Redirect("b.aspx")的区别
收藏 0 赞 0 分享

ASP.NET Gridview与checkbox全选、全不选实现代码

ASP.NET Gridview checkbox全选与全不选实现代码,其实原理就是利用js来实现的,但需要简单的设置下回传。
收藏 0 赞 0 分享

ASP.NET DropDownList控件的使用方法

ASP.NET DropDownList控件的使用方法,学习asp.net的朋友没用过这个控件的朋友可以参考下。
收藏 0 赞 0 分享

一些.NET对多线程异常处理技巧分享

多线程应用,在实际的项目或产品开发中,原则上来说,应该尽量避免,但是在强调用户体验的要求下或开发平台的限制下(如 Silverlight Socket 通讯),我们不得不用多线程。
收藏 0 赞 0 分享

ASP.NET MVC运行出现Uncaught TypeError: Cannot set property __MVC_FormValidation of null的解决方法

同一相站点,有些页面的客户端验证能工作,而有些死活不行。打开页面就出现Uncaught TypeError: Cannot set property __MVC_FormValidation of null错误
收藏 0 赞 0 分享

asp.net 通用分页显示辅助类(改进版)

在使用ASP.NET编程时,如果不用控件的默认分页功能,想自己搞一个,可以看看本文的asp.net通用分页显示辅助类哦。
收藏 0 赞 0 分享

微软 Visual Studio 2010官方下载地址给大家

昨天VS2010在网上报道都已经发布了,现在今天在网上找到Visual Studio 2010官方下载地址,提供给大家下载。
收藏 0 赞 0 分享

Javascript 直接调用服务器C#代码 ASP.NET Ajax实例

近来总有一些朋友会问到一些入门的问题,把这些问题整理一下,写出来。在以前的文章里,曾经利用纯JS编写过Ajax引擎,在真正开发的时候,大家都不喜欢以这种低效率的方式开发,利用MS Ajax的集成的引擎,可以简单不少工作。
收藏 0 赞 0 分享

ASP.NET 页面刷新的实现方法(包括html,js)

ASP.NET 页面刷新的实现方法,比较全了, 包括html与js下的实现方法。
收藏 0 赞 0 分享

asp.net 无刷新翻页就是这么简单

前两天看了一个自定义分页控件,和AspNetPager一样是实现IPostBackEventHandler接口,不过简洁许多,就想能不能实现ICallbackEventHandler接口做到无刷新分页呢?想到了就马上去做,终于,设想变成了现实!!
收藏 0 赞 0 分享
查看更多