网页前端设计

http://www.86y.org

搜索文章

jq+ashx图片单点上传支持一个页面多次调用

用声音读出全文关注我吧
 2015/7/2 20:17:14 阅读次数:6578

本人一直在前端做效果切图,趁着晚上有空写点笔记记录下。效果就是AJAX上传图片不错的效果,最大的特点是支持多个同时在页面中调用。(底部附源代码下载)

效果如下图:

jq+ashx图片单点上传支持一个页面多次调用

本代码使用说明:

1、支持水印,可以启用图片或文字(可以传参数?iswater=1);

2、支持是否生成缩略图,并且要指定高宽大小(可作为参数传递?width=*&height=*);

3、上传文件类型及文件大小限止大小;(需要在ashx文件中设置)。

前端代码如下:(uploadimg.html)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadimg.aspx.cs" Inherits="uploadimg" %>
<!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>    
    <link href="css/upload.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="imgupload">
            <div class="img"><img src="images/blankbg.gif" /></div>
            <div class="upload">图片上传<input type="file" name="upload1" id="uploadfile" class="uploadfile" /></div>
            <div class="edit upload">重新上传<input type="file" name="upload2" id="File2" class="uploadfile" /></div>
        </div>

        <div class="imgupload">
            <div class="img"><img src="images/blankbg.gif" /></div>
            <div class="upload">图片上传<input type="file" name="upload3" id="File1" class="uploadfile" /></div>
            <div class="edit upload">重新上传<input type="file" name="upload4" id="File3" class="uploadfile" /></div>
        </div>
    </form>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script src="js/jquery-form.js"></script>
    <script>
        $(function () {
            $(".uploadfile").change(function (index) {
                var obj = $(this);
                $("#form1").ajaxSubmit({
                    url: '/ashx/uploadfile.ashx?index=' + $(this).attr("name") + '&iswater=1&ram=' + Math.random(),
                    beforeSubmit: function () {                        
                        $(index.target).parent().parent().addClass("loading");//上传中
                    },
                    success: function (data) {
                        if (data.toString().indexOf("upload") > -1) {
                            if ($.browser.msie) {
                                data = data.replace("<pre>", "").replace("</pre>", "").replace("<PRE>", "").replace("</PRE>", "");
                            }
                            $(index.target).parent().parent().removeClass("loading");
                            $(index.target).parent().parent().addClass("ed");
                            $(index.target).parent().parent().find("img").eq(0).fadeIn(1000)
                            $(index.target).parent().parent().find("img").eq(0).attr("src", data);
                        }
                        else {
                            alert("上传失败"+data);
                        }
                    }
                });
            });
        });

    </script>
</body>
</html

后台功能代码如下:(uploadfile.ashx)

<%@ WebHandler Language="C#" Class="uploadfile" %>

using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Web.SessionState;

public class uploadfile : IHttpHandler, IReadOnlySessionState
{

    string upext = "jpg,jpeg,gif,png,swf";    // 上传扩展名
    string Uplogo = "jpg,jpeg,gif,png"; //用来判断是图片是增加水印
    string attachdir = "upload";     // 上传文件保存路径,结尾不要带/
    bool iswater = false;           //默认没有水印
    Int32 maxsize = 2 * 1024 * 1024;//最大上传文件2M
    public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "text/plain";
    string filename, target, targets, targetnew, extension;
    if (context.Request["iswater"] != null && context.Request["iswater"].ToString() == "1")
    {
        iswater = true;
    }
        
    string index = ""; 
    if (context.Request.QueryString["index"] != null)
    {
        index = context.Request.QueryString["index"].ToString();
    }

    HttpPostedFile File1 = context.Request.Files[index];
    string path = File1.FileName;
    extension = Path.GetExtension(File1.FileName).ToLower();
    Random random = new Random(DateTime.Now.Millisecond);
    filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000);
    attachdir = attachdir + "/" + DateTime.Now.ToString("yyyyMMdd");

    // 生成随机文件名

    if (File1.ContentLength <= maxsize)
    {

        target = attachdir + "/" + filename + extension;
        targets = attachdir + "/s" + filename + extension;
        targetnew = attachdir + "/" + filename + "_new" + extension;
        CreateFolder(context.Server.MapPath("../" + attachdir));
        File1.SaveAs(context.Server.MapPath("../" + target));

        #region 判断是否生成缩略图
        if (context.Request["width"] != null && context.Request["height"] != null)
        {
            int width = 0;
            int height = 0;
            int.TryParse(context.Request["width"].ToString(), out width);
            int.TryParse(context.Request["height"].ToString(), out height);
            if (width > 0 && height > 0)
            {
                System.Drawing.Image g;
                g = System.Drawing.Image.FromFile(context.Server.MapPath("../" + target));
                System.Drawing.Image g2 = new System.Drawing.Bitmap(g, width, height);

                g2.Save(context.Server.MapPath("../" + targets));
                g2.Dispose();
                g.Dispose();
            }


        }
        #endregion

        #region 加图片水印
        if ((Uplogo.IndexOf(extension.Replace(".", "")) >= 0) && iswater)
        {
            string Sitename = "", Seourl = "";
            if (context.Request.QueryString["Sitename"] != null) Sitename = context.Request.QueryString["Sitename"].ToString();
            if (context.Request.QueryString["Seourl"] != null) Seourl = context.Request.QueryString["Seourl"].ToString();

            //加文字水印,注意,这里的代码和以下加图片水印的代码不能共存
            //System.Drawing.Image image = System.Drawing.Image.FromFile(context.Server.MapPath("../" + target));
            //Graphics g = Graphics.FromImage(image);
            //g.DrawImage(image, 0, 0, image.Width, image.Height);
            //Font fn = new Font("Verdana", 16);
            //Brush b = new SolidBrush(Color.Red);
            //string addText = Sitename + "\n" + Seourl;
            //g.DrawString(addText, fn, b,image.Width- 200,image.Height - 60);
            //g.Dispose();

            ////加图片水印

            System.Drawing.Image image = System.Drawing.Image.FromFile(context.Server.MapPath("../" + target));


            if (image.Width > 120 && image.Height > 40)
            {
                System.Drawing.Image copyImage = System.Drawing.Image.FromFile(context.Server.MapPath("../images/water.png"));
                Graphics g = Graphics.FromImage(image);

                g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);

                g.Dispose();

                //保存加水印过后的图片,删除原始图片
                image.Save(context.Server.MapPath("../" + targetnew));

                image.Dispose();

                if (File.Exists(context.Server.MapPath("../" + target)))
                {

                    File.Delete(context.Server.MapPath("../" + target));
                    File.Move(context.Server.MapPath("../" + targetnew), context.Server.MapPath("../" + target));

                }
                //target = targetnew;  //直接返回小图
            }
        }
        #endregion
        context.Response.Write("/" + target);
    }
    else
    {
        context.Response.Write("上传文件不能超2M");
    }
        
       
    }   
    
    string GetFileExt(string FullPath)
    {
        if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
        else return "";
    }

    void CreateFolder(string FolderPath)
    {
        if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
    }
    bool Logocheck(string Ext)
    {
        if (upext.ToString().IndexOf(Ext) >= 0) return true;
        else return false;

    }    
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

总结

本人经过IE6+,FF,chrome,360等浏览器测试上传成功,效果不错,大家可以通过自己的想象做出更好的效果。

源代码下载地址:http://pan.baidu.com/s/1sl2Fxrn 密码: 9wt9


大家有什么问题或技术上的想法可以在此与大家分享,也可以加入前端爱好者QQ群(141999928)一起学习进步:【幸凡前端技术交流群】
如需转载请注明出处:http://www.86y.org/art_detail.aspx?id=749【jq+ashx图片单点上传支持一个页面多次调用】幸凡学习网
0

如果您觉得本文的内容对您的学习有所帮助,捐赠与共勉,支付宝(左)或微信(右)

阅读全文内容关闭