SWFUpload上传文件

一、SWFUpload介绍

1. 首先为什么要使用该组建进行上传文件?而不使用以往的上传文件的方式。

答:因为以往的上传文件会造成表单页面的刷新。这样上传文件会很不方便。但是SWFUpload能够很好的解决该困惑。

二、 SWFUpload的使用,建议去看看别人写的demo,然后再去使用该插件。

1. 首先需要引入相关的js文件

 <script src="../js/jquery-1.7.1.js"></script>    //jquery组件
<script src="../SWFUpload/swfupload.js"></script> <script src="../SWFUpload/handlers.js"></script>

2. 其核心代码和配置是如下代码。复制到自己的编辑器中研究一下。其中修改了配置项对应的upload_success_handler返回成功的事件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CutPhoto.aspx.cs" Inherits="BookShop.Web.Member.CutPhoto" %>

<!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/themes/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" />
       <script src="../js/jquery-1.7.1.js"></script>
    <script src="../js/jquery-ui-1.8.2.custom.min.js"></script>
    <script src="../SWFUpload/swfupload.js"></script>
    <script src="../SWFUpload/handlers.js"></script>
      <script type="text/javascript">
          var swfu;
          window.onload = function () {
              swfu = new SWFUpload({
                  // Backend Settings
                  upload_url: "/ashx/upload.ashx?action=upload",
                  post_params: {
                      "ASPSESSID": "<%=Session.SessionID %>"
                },

                // File Upload Settings
                file_size_limit: "2 MB",
                file_types: "*.jpg;*.gif",
                file_types_description: "JPG Images",
                file_upload_limit: 0,    // Zero means unlimited

                // Event Handler Settings - these functions as defined in Handlers.js
                //  The handlers are not part of SWFUpload but are part of my website and control how
                //  my website reacts to the SWFUpload events.
                swfupload_preload_handler: preLoad,
                swfupload_load_failed_handler: loadFailed,
                file_queue_error_handler: fileQueueError,
                file_dialog_complete_handler: fileDialogComplete,
                upload_progress_handler: uploadProgress,
                upload_error_handler: uploadError,
                upload_success_handler: showImage,
                upload_complete_handler: uploadComplete,

                // Button settings
                button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png",
                button_placeholder_id: "spanButtonPlaceholder",
                button_ 160,
                button_height: 22,
                button_text: '<span class="button">请选择上传图片<span class="buttonSmall">(2 MB Max)</span></span>',
                button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
                button_text_top_padding: 1,
                button_text_left_padding: 5,

                // Flash Settings
                flash_url: "/SWFUpload/swfupload.swf",    // Relative to this file
                flash9_url: "/SWFUpload/swfupload_FP9.swf",    // Relative to this file

                custom_settings: {
                    upload_target: "divFileProgressContainer"
                },

                // Debug Settings
                debug: false
            });
        }
        //上传成功以后调用该方法
        function showImage(file, serverData) {
            // $("#showPhoto").attr("src", serverData);
            var data = serverData.split(':');   //先将字符串分割,分割出图片的高度和宽度
            //将上传成功的图片作为DIV的背景
            $("#hiddenImageUrl").val(data[0]);//将上传成功的图片路径存储到隐藏域中。
            //设置图片路径和设置其宽度和高度
            $("#divContent").css("backgroundImage", "url('" + data[0] + "')").css("width",data[1]+"px").css("height",data[2]+"px");
        }

        $(function () {
            //让DIV可以(draggable)移动与(resizable)拖动大小
            $("#divCut").draggable({ containment: "#divContent", scroll: false }).resizable({
                containment: "#divContent"
            });

            //添加单击事件,截图头像
            $("#btnCut").click(function () {
                cutPhoto();
            });
        })
          //截取头像
        function cutPhoto() {
            //计算要截取的头像的范围。  offset(计算出该div距离浏览器顶部的距离)
            var y = $("#divCut").offset().top - $("#divContent").offset().top;//纵坐标
            var x = $("#divCut").offset().left - $("#divContent").offset().left;
            //获取宽度和高度,都是由jQuery封装好的方法
            var width = $("#divCut").width();
            var heigth = $("#divCut").height();
            var pars = {
                "x": x,
                "y": y,
                "width": width,
                "height": heigth,
                "action": "cut",
                "imgSrc": $("#hiddenImageUrl").val()
                
            };
            $.post("/ashx/upload.ashx", pars, function (data) {
                $("#showPhoto").attr("src",data);
            });

        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
   <div id="content">
        <div id="swfu_container" style="margin: 0px 10px;">
            <div>
                <span id="spanButtonPlaceholder"></span>
            </div>
            <div id="divFileProgressContainer" style="height: 75px;"></div>
            <div id="thumbnails"></div>
            <div id="divContent" style="300px; height:300px;">
                <div id="divCut" style="100px;height:100px; border:solid red 1px">
                </div>

            </div>
            <input type="button" value="截取图片" id="btnCut" />
            <input type="hidden" id="hiddenImageUrl" />
            <img id="showPhoto"></img>
        </div>
        </div>
    </form>
</body>
</html>

对应的请求。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;

namespace BookShop.Web.ashx
{
    /// <summary>
    /// upload 的摘要说明
    /// </summary>
    public class upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];
            if (action == "upload")//上传图片
            {
                ProcessFileUpload(context);
            }
            else if (action =="cut")//截取图片
            {
                ProcessCutPhoto(context);
            }
            else
            {
                context.Response.Write("参数错误!!");
            }
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="context"></param>
        private void ProcessFileUpload(HttpContext context)
        {
            HttpPostedFile file = context.Request.Files["Filedata"];
            if (file != null)
            {
                //获取文件名和扩展名
                string fileName = Path.GetFileName(file.FileName);
                string fileExt = Path.GetExtension(fileName);
                //如果扩展名等于。jpg
                if (fileExt == ".jpg")
                {
                    string dir = "/ImageUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                    if (!Directory.Exists(context.Request.MapPath(dir)))
                    {
                        Directory.CreateDirectory(context.Request.MapPath(dir));
                    }
                    string newfileName = Guid.NewGuid().ToString();
                    string fullDir = dir + newfileName + fileExt;
                    file.SaveAs(context.Request.MapPath(fullDir));
                    //生成一个image的实例,取出上传图片的高度和宽度
                    using (Image img = Image.FromFile(context.Request.MapPath(fullDir)))
                    {
                        context.Response.Write(fullDir + ":" + img.Width + ":" + img.Height);
                    }

                    //file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName));
                    //context.Response.Write("/ImageUpload/" + fileName);
                }
            }
        }

        /// <summary>
        /// 图片的截取
        /// </summary>
        /// <param name="context"></param>
        private void ProcessCutPhoto(HttpContext context)
        {
            int x = Convert.ToInt32(context.Request["x"]);
            int y = Convert.ToInt32(context.Request["y"]);
            int width = Convert.ToInt32(context.Request["width"]);
            int height = Convert.ToInt32(context.Request["height"]);
            string imgSrc = context.Request["imgSrc"];//获取上传成功的图片的路径
            //创建一个画布
            using (Bitmap map = new Bitmap(width, height))
            {
                //创建一个画笔
                using (Graphics g = Graphics.FromImage(map))
                {
                    //new一个image对象,
                    using (Image img = Image.FromFile(context.Request.MapPath(imgSrc)))
                    {
                        //第一个参数:表示画哪张图片.
                        //二:画多么大。
                        //三:画原图的哪块区域
                        g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
                        string newfileName = Guid.NewGuid().ToString();
                        string fullDir = "/ImageUpload/" + newfileName + ".jpg";
                        map.Save(context.Request.MapPath(fullDir),System.Drawing.Imaging.ImageFormat.Jpeg);
                        context.Response.Write(fullDir);

                    }
                   
                }
            }
        }

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

3.  imageAreaSelect插件使用:利用该插件截取图片,其中后端代码不变,还是和上方一样。但是此处需要引入相关的文件。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CutPhoto.aspx.cs" Inherits="BookShop.Web.Member.CutPhoto" %>

<!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/themes/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" />--%>
    <link href="../Css/imgareaselect-default.css" rel="stylesheet" />
       <script src="../js/jquery-1.7.1.js"></script>
   <%-- <script src="../js/jquery-ui-1.8.2.custom.min.js"></script>--%>
    <script src="../js/jquery.imgareaselect.min.js"></script>
    <script src="../SWFUpload/swfupload.js"></script>
    <script src="../SWFUpload/handlers.js"></script>
      <script type="text/javascript">
          var swfu;
          window.onload = function () {
              swfu = new SWFUpload({
                  // Backend Settings
                  upload_url: "/ashx/upload.ashx?action=upload",
                  post_params: {
                      "ASPSESSID": "<%=Session.SessionID %>"
                },

                // File Upload Settings
                file_size_limit: "2 MB",
                file_types: "*.jpg;*.gif",
                file_types_description: "JPG Images",
                file_upload_limit: 0,    
                swfupload_preload_handler: preLoad,
                swfupload_load_failed_handler: loadFailed,
                file_queue_error_handler: fileQueueError,
                file_dialog_complete_handler: fileDialogComplete,
                upload_progress_handler: uploadProgress,
                upload_error_handler: uploadError,
                upload_success_handler: showImage,
                upload_complete_handler: uploadComplete,

                // Button settings
                button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png",
                button_placeholder_id: "spanButtonPlaceholder",
                button_ 160,
                button_height: 22,
                button_text: '<span class="button">请选择上传图片<span class="buttonSmall">(2 MB Max)</span></span>',
                button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
                button_text_top_padding: 1,
                button_text_left_padding: 5,

                // Flash Settings
                flash_url: "/SWFUpload/swfupload.swf",    // Relative to this file
                flash9_url: "/SWFUpload/swfupload_FP9.swf",    // Relative to this file

                custom_settings: {
                    upload_target: "divFileProgressContainer"
                },

                // Debug Settings
                debug: false
            });
        }
        //上传成功以后调用该方法
        function showImage(file, serverData) {
            var data = serverData.split(':');
            $("#selectbanner").attr("src", data[0]);
            $('#selectbanner').imgAreaSelect({
                selectionColor: 'blue', x1: 0, y1: 0, x2: 100,
                y2: 100,selectionOpacity: 0.2, onSelectEnd: preview
            });

        }
          //选择结束以后调用该方法
        function preview(img, selection) {
            $('#selectbanner').data('x', selection.x1);
            $('#selectbanner').data('y', selection.y1);
            $('#selectbanner').data('w', selection.width);
            $('#selectbanner').data('h', selection.height);
        }
        $(function () {
            $("#btnCut").click(function () {
                cutPhoto();
            });
        })
          //截取头像
        function cutPhoto() {
            var pars = {
                "x": $('#selectbanner').data('x'),

                "y": $('#selectbanner').data('y'),

                "width": $('#selectbanner').data('w'),

                "height": $('#selectbanner').data('h'),
                "action": "cut",
                "imgSrc": $("#selectbanner").attr("src")
                
            };
            $.post("/ashx/upload.ashx", pars, function (data) {
                $("#showPhoto").attr("src",data);
            });

        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
   <div id="content">
        <div id="swfu_container" style="margin: 0px 10px;">
            <div>
                <span id="spanButtonPlaceholder"></span>
            </div>
            <div id="divFileProgressContainer" style="height: 75px;"></div>
            <div id="thumbnails"></div>
            <input type="button" value="截取图片" id="btnCut" />
            <input type="hidden" id="hiddenImageUrl" />
            
            <img id="selectbanner" />
            <img id="showPhoto"/>


        </div>
        </div>
    </form>
</body>
</html>
原文地址:https://www.cnblogs.com/wangjinya/p/10634357.html