• [ASP.NET]使用uploadify上传图片,并在uploadify按钮上生成预览图


    目录

    需求

    主要代码

    总结

    需求

    项目中有用到uploadify上传插件,给的原型就是上传成功后替换原来的图片。没办法需求在那儿,也不能修改需求吧,只能想办法解决问题了。

    主要代码

    修改uploadify样式:

     1 /*
     2 Uploadify
     3 Copyright (c) 2012 Reactive Apps, Ronnie Garcia
     4 Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
     5 */
     6 
     7 .uploadify {
     8     position: relative;
     9     margin-bottom: 1em;
    10     color:blue;
    11 }
    12 
    13 /*.uploadify-button {
    14     background-color: #505050;
    15     background-image: linear-gradient(bottom, #505050 0%, #707070 100%);
    16     background-image: -o-linear-gradient(bottom, #505050 0%, #707070 100%);
    17     background-image: -moz-linear-gradient(bottom, #505050 0%, #707070 100%);
    18     background-image: -webkit-linear-gradient(bottom, #505050 0%, #707070 100%);
    19     background-image: -ms-linear-gradient(bottom, #505050 0%, #707070 100%);
    20     background-image: -webkit-gradient(
    21         linear,
    22         left bottom,
    23         left top,
    24         color-stop(0, #505050),
    25         color-stop(1, #707070)
    26     );
    27     background-position: center top;
    28     background-repeat: no-repeat;
    29     -webkit-border-radius: 30px;
    30     -moz-border-radius: 30px;
    31     border-radius: 30px;
    32     border: 2px solid #808080;
    33     color: #FFF;
    34     font: bold 12px Arial, Helvetica, sans-serif;
    35     text-align: center;
    36     text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
    37      100%;
    38 }
    39 .uploadify:hover .uploadify-button {
    40     background-color: #606060;
    41     background-image: linear-gradient(top, #606060 0%, #808080 100%);
    42     background-image: -o-linear-gradient(top, #606060 0%, #808080 100%);
    43     background-image: -moz-linear-gradient(top, #606060 0%, #808080 100%);
    44     background-image: -webkit-linear-gradient(top, #606060 0%, #808080 100%);
    45     background-image: -ms-linear-gradient(top, #606060 0%, #808080 100%);
    46     background-image: -webkit-gradient(
    47         linear,
    48         left bottom,
    49         left top,
    50         color-stop(0, #606060),
    51         color-stop(1, #808080)
    52     );
    53     background-position: center bottom;
    54 }*/
    55 .uploadify-button.disabled {
    56     background-color: #D0D0D0;
    57     color: #808080;
    58 }
    59 .uploadify-queue {
    60     margin-bottom: 1em;
    61 }
    62 .uploadify-queue-item {
    63     background-color: #F5F5F5;
    64     -webkit-border-radius: 3px;
    65     -moz-border-radius: 3px;
    66     border-radius: 3px;
    67     font: 11px Verdana, Geneva, sans-serif;
    68     margin-top: 5px;
    69     max-width: 350px;
    70     padding: 10px;
    71 }
    72 .uploadify-error {
    73     background-color: #FDE5DD !important;
    74 }
    75 .uploadify-queue-item .cancel a {
    76     background: url('../img/uploadify-cancel.png') 0 0 no-repeat;
    77     float: right;
    78     height:    16px;
    79     text-indent: -9999px;
    80     width: 16px;
    81 }
    82 .uploadify-queue-item.completed {
    83     background-color: #E5E5E5;
    84 }
    85 .uploadify-progress {
    86     background-color: #E5E5E5;
    87     margin-top: 10px;
    88     width: 100%;
    89 }
    90 .uploadify-progress-bar {
    91     background-color: #0099FF;
    92     height: 3px;
    93     width: 1px;
    94 }

    将uploadify默认样式注释。
    上传按钮代码:

    1  <input type="hidden" id="hdId" name="name" value="1" />
    2             <img src="../images/logo/logo.png" alt="图标" id="imgUpload" />

    uploadify是基于flash的上传插件,在客户端生成的是object对象。

    通过上图可知,设置的img上传按钮在客户端由div代替,id变为imgUpload-button。知道id了就好办了。

    js代码:

     1     <link href="JS/uploadify/css/uploadify.css" rel="stylesheet" />
     2     <script type="text/javascript" src="JS/jquery-1.8.0.min.js"></script>
     3     <script type="text/javascript" src="JS/uploadify/js/uploadify3.2.1/jquery.uploadify.js"></script>
     4     <script type="text/javascript">
     5         $(function () {
     6             //初始化上传插件
     7             InitUploadify("imgUpload");
     8         });
     9         function InitUploadify(id) {
    10 
    11             //上传插件初始化方法
    12             $('#' + id).uploadify({
    13                 //选择文件后是否自动上传,默认为true
    14                 'auto': true,
    15                 //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值 上传大文件 可参考使用手册说明               
    16                 'fileSizeLimit': '2MB',
    17                 'width': 40,
    18                 'height': 40,
    19                 //文件描述
    20                 'fileTypeDesc': 'Files',
    21                 //允许上传的文件类型 以分号分割
    22                 'fileTypeExts': '*.gif; *.jpg; *.png;',
    23                 //请求方式"get"或者"post",默认为"post"   
    24                 'method': 'post',
    25                 //是否允许同时选择多个文件,默认为true
    26                 'multi': false,
    27                 'buttonImage': '../images/logo/logo.png',
    28                 //队列的ID,一个存放上传文件div的ID
    29                 'queueID': 'fileQueue',
    30                 //FLash文件路径
    31                 'swf': '/JS/uploadify/js/uploadify3.2.1/uploadify.swf',
    32                 'onUploadStart': function (file) {
    33                     //传递参数
    34                     $("#" + id).uploadify("settings", "formData", { 'strId': $("#hdId").val() });
    35                 },
    36                 //上传文件处理后台页面
    37                 'uploader': 'UploadImgHandler.ashx',
    38                 //重写错误事件,否则在关闭自定义错误提示框后,扔弹出默认的英文信息
    39                 'overrideEvents': ['onSelectError', 'onDialogClose'],
    40                 //返回一个错误,选择文件的时候触发 
    41                 'onSelectError': function (file, errorCode, errorMsg) {
    42                     switch (errorCode) {
    43                         case -100:
    44                             alert("上传的文件数量已经超出系统限制的" + $("#" + id).uploadify('settings', 'queueSizeLimit') + "个文件!");
    45                             break;
    46                         case -110:
    47                             alert("文件 [" + file.name + "] 大小超出系统限制的" + $("#" + id).uploadify('settings', 'fileSizeLimit') + "大小!");
    48                             break;
    49                         case -120:
    50                             alert("文件 [" + file.name + "] 大小异常!");
    51                             break;
    52                         case -130:
    53                             alert("文件 [" + file.name + "] 类型不正确!");
    54                             break;
    55                     }
    56                 },
    57                 //检测FLASH失败调用 
    58                 'onFallback': function () {
    59                     alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
    60                 },
    61                 //上传成功后触发,每个文件都触发
    62                 'onUploadSuccess': function (file, data, response) {
    63                     var result = eval('(' + data + ')');
    64                     if (result.imgSrc != "0") {
    65                         //置换按钮的背景图,uploadify在客户端生成的id为imgUpload-button
    66                         $("#imgUpload-button").css("background-image", "url('" + result.imgSrc + "')").attr({ "src": result.imgSrc });
    67                     } else {
    68                         alert("上传失败");
    69                     }
    70                 }
    71 
    72             });
    73         }
    74     </script>

    需要注意,上面采用了自定义错误提示,需要

    1  //重写错误事件,否则在关闭自定义错误提示框后,扔弹出默认的英文信息
    2                 'overrideEvents': ['onSelectError', 'onDialogClose'],

    不然在弹出自定义的错误信息后,关闭错误信息仍会出现英文错误信息。
    将该句注释后,测试结果:

    单击确定后

    所以在自定义错误提示信息时需要重写事件。

     ['onSelectError', 'onDialogClose']

    接收上传图片的一般处理程序代码:

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Drawing;
      4 using System.IO;
      5 using System.Linq;
      6 using System.Web;
      7 
      8 namespace Wolfy.UploadifyImageDemo
      9 {
     10     /// <summary>
     11     /// UploadImgHandler 的摘要说明
     12     /// </summary>
     13     public class UploadImgHandler : IHttpHandler
     14     {
     15 
     16         public void ProcessRequest(HttpContext context)
     17         {
     18             context.Response.ContentType = "text/plain";
     19             //获取上传的文件
     20             HttpPostedFile httpPostedFile = context.Request.Files["Filedata"];
     21 
     22             //如果接收到文件则httpPostedFile不为null,则对上传的文件进行处理,否则向客户端返回0
     23             if (httpPostedFile != null)
     24             {
     25                 //获取文件名
     26                 string strfileName = httpPostedFile.FileName;
     27 
     28                 //获取扩展名
     29                 string strExt = Path.GetExtension(strfileName);
     30 
     31                 //允许上传的文件类型
     32                 string[] strExts = { ".jpg", ".png", ".gif" };
     33 
     34                 //如果上传的文件类型,在被允许的类型中,则保存,否则向客户端输出“不允许上传”的信息提示。
     35                 if (strExts.Contains(strExt))
     36                 {
     37                     string strSaveName = string.Empty;
     38                     string strSavePath = ConvertImageByWH(context, httpPostedFile.InputStream, 50, 50, strExt, out strSaveName);
     39 
     40                     string strJson = " { 'imgSrc': '" + strSavePath + "'} ";
     41                     //将文件的保存的相对路径输出到客户端
     42                     context.Response.Write(strJson);
     43 
     44                 }
     45                 else
     46                 {
     47                     context.Response.Write("{'imgSrc':'0'}");
     48                 }
     49             }
     50         }
     51         /// <summary>
     52         /// 按照给定的宽高对图片进行压缩
     53         /// </summary>
     54         /// <param name="byteImg">图片字节流</param>
     55         /// <param name="intImgCompressWidth">压缩后的图片宽度</param>
     56         /// <param name="intImgCompressHeight">压缩后的图片高度</param>
     57         /// <param name="strExt">扩展名</param>
     58         /// <param name="strSaveName">保存后的名字</param>
     59         /// <returns>压缩后的图片相对路径</returns>
     60         private string ConvertImageByWH(HttpContext context, Stream stream, int intImgCompressWidth, int intImgCompressHeight, string strExt, out string strSaveName)
     61         {
     62             //从输入流中获取上传的image对象
     63             using (System.Drawing.Image img = System.Drawing.Image.FromStream(stream))
     64             {
     65                 //根据压缩比例求出图片的宽度
     66                 int intWidth = intImgCompressWidth / intImgCompressHeight * img.Height;
     67                 int intHeight = img.Width * intImgCompressHeight / intImgCompressWidth;
     68                 //画布
     69                 using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img, new Size(intImgCompressWidth, intImgCompressHeight)))
     70                 {
     71                     //在画布上创建画笔对象
     72                     using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
     73                     {
     74                         //将图片使用压缩后的宽高,从0,0位置画在画布上
     75                         graphics.DrawImage(img, 0, 0, intImgCompressWidth, intImgCompressHeight);
     76                         //创建保存路径
     77                         string strSavePath = "/images/logo/";
     78 
     79                         //如果保存目录不存在,则创建
     80                         if (!Directory.Exists(context.Server.MapPath(strSavePath)))
     81                         {
     82                             Directory.CreateDirectory(context.Server.MapPath(strSavePath));
     83                         }
     84                         //定义新的文件名
     85                         string strfileNameNoExt = string.Empty;
     86                         //接收参数
     87                         string strId = context.Request.Params["strId"];
     88                         if (!string.IsNullOrEmpty(strId))
     89                         {
     90                             if (strId == "1")
     91                             {
     92                                 //定义新的文件名
     93                                 strfileNameNoExt = Guid.NewGuid().ToString();
     94                             }
     95                         }
     96 
     97                         strSaveName = strfileNameNoExt + strExt;
     98                         //添加时如果图片已经存在则删除
     99                         if (File.Exists(context.Server.MapPath(strSavePath) + strSaveName))
    100                         {
    101                             File.Delete(context.Server.MapPath(strSavePath) + strSaveName);
    102                         }
    103                         //保存文件
    104                         bitmap.Save(context.Server.MapPath(strSavePath) + strSaveName);
    105                         return strSavePath + strSaveName;
    106                     }
    107                 }
    108             }
    109         }
    110         public bool IsReusable
    111         {
    112             get
    113             {
    114                 return false;
    115             }
    116         }
    117     }
    118 }
    View Code

    测试结果:
    默认:

    上传成功后:

    总结

    在项目中多少会用到一些插件,但是又不能完全适应需求,这时就需要对其进行定制的修改,这时候F12还是很管用的。

  • 相关阅读:
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
  • 原文地址:https://www.cnblogs.com/wolf-sun/p/3963233.html
Copyright © 2020-2023  润新知