欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-02 12:09:16
前台代码: 复制代码 代码如下: <%@ page language="c#" autoeventwireup="true" codefile="uplo...

前台代码:

复制代码 代码如下:


 <%@ 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

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