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

 更新时间:2013年04月15日 21:56:58   作者:  
今天写了一个上传多张图片并生成缩略图的小程序。当然因为是菜鸟,所以写的一般。但还是学到了不少东西。现在上代码。

前台代码:

复制代码 代码如下:


 <%@ 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下PageMethods使用技巧

    asp.net下PageMethods使用技巧

    ASP.net AjAX中的PageMethods可以将静态页方法添加到 ASP.NET 页中并将其用作 Web 方法。然后,无需创建单独的 .asmx 文件即可从该页中的脚本调用这些方法,就好像这些方法是 Web 服务的一部分。特别是在一些交互流程不复杂而调用次数和方法又比较多的情况下更为方便。因为PageMethods不需要我们再添加另外的WEB服务或Page来处理请求。
    2008-03-03
  • asp.net使用jQuery Uploadify上传附件示例

    asp.net使用jQuery Uploadify上传附件示例

    Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示,本文是一个简单的介绍Demo,主要是动态传递参数方法,通过formdata 向处理程序传递额外的表单数据
    2014-01-01
  • ASP.NET简化编辑界面解决思路及实现代码(2)

    ASP.NET简化编辑界面解决思路及实现代码(2)

    这篇与前一篇改进部分,也许大家会留意到动画演示,主要是GridVeiw的更新与删除会在每row都有。因此Insus.NET把它抽取出来,放在GridView外,感兴趣的朋友可以了解下啊,希望本文对你有所帮助
    2013-01-01
  • .NET MVC中ViewData,ViewBag和TempData的区别浅析

    .NET MVC中ViewData,ViewBag和TempData的区别浅析

    这篇文章主要介绍了.NET MVC中ViewData,ViewBag和TempData的区别,分析了ViewData,ViewBag和TempData在赋值、功能特性等方面的区别于用法,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-01-01
  • asp.net+ajax的Post请求实例

    asp.net+ajax的Post请求实例

    这篇文章主要介绍了asp.net+ajax的Post请求实现方法,实例分析了Ajax的发送post数据的原理与技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-01-01
  • asp.net Application_AcquireRequestState事件,导致Ajax客户端不能加载

    asp.net Application_AcquireRequestState事件,导致Ajax客户端不能加载

    项目中使用Application_AcquireRequestState事件,来做一些用户信息的验证工作.
    2010-03-03
  • .net中 发送邮件内容嵌入图片的具体实例

    .net中 发送邮件内容嵌入图片的具体实例

    这篇文章主要介绍了.net中 发送邮件内容嵌入图片的具体实例,需要的朋友可以参考下
    2014-02-02
  • 利用ASP.NET MVC和Bootstrap快速搭建响应式个人博客站(一)

    利用ASP.NET MVC和Bootstrap快速搭建响应式个人博客站(一)

    这篇文章主要介绍了利用ASP.NET MVC和Bootstrap快速搭建响应式个人博客站(一)的相关资料,需要的朋友可以参考下
    2016-06-06
  • .NET微信公众号查看关注者接口

    .NET微信公众号查看关注者接口

    这篇文章主要为大家详细介绍了.NET微信公众号查看关注者接口的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • asp.net String.Empty NULL 不同之处

    asp.net String.Empty NULL 不同之处

    在asp.net(c#)中String.Empty、NULL、"" 3个语法经常使用,作用是判断字符串是否为空。
    2009-06-06

最新评论