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

文件上传之——用SWF插件实现文件异步上传和头像截取

程序员文章站 2022-05-01 20:37:25
...
之前写过几篇文件上传,那些都不错。今天小编带领大家体会一种新的上传方法,及使用Flash插件实现文件上传。

使用Flash的好处就是可以解决浏览器兼容性问题。之前我写的一个快捷复制功能也是利用的Flash。

最近一直在用MVC,所以还是以MVC举例;先来张效果图:

文件上传之——用SWF插件实现文件异步上传和头像截取文件上传之——用SWF插件实现文件异步上传和头像截取

文件上传之——用SWF插件实现文件异步上传和头像截取

UploadIndex2.cshtml代码:

文件上传之——用SWF插件实现文件异步上传和头像截取
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
    <title>上传</title>
    <script src="~/SWFUpload/swfupload.js" type="text/javascript"></script>
    <script src="~/SWFUpload/handlers.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        var swfu;
        window.onload = function () {
            swfu = new SWFUpload({
                // Backend Settings
                upload_url: "@Url.Action("HandlerUpload2","Home")",//上传路径
                post_params: {
                    "ASPSESSID": "<@Session.SessionID>"
                },

                // File Upload Settings
                file_size_limit: "5 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: showData,
                upload_complete_handler: uploadComplete,

                // Button settings
                button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png",//设置按钮图片,注意要是连续的四张
                button_placeholder_id: "spanButtonPlaceholder",//设置按钮id
                button_width: 160,
                button_height: 22,
                button_text: '<span class="button">请选择上传图片 <span class="buttonSmall">(5 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 showData(file, serverData) {
            $("#imgSrc").attr("src", serverData);
        }
    </script>
</head>
<body>
    <form id="form1">

        <div id="content">

            <div id="swfu_container" style="margin: 0px 10px;">
                <div>                 
                    <span id="spanButtonPlaceholder"></span>  <!--注意:这个ID要和上面的一致-->                
                </div>                          
             
             
                <img id="imgSrc" /><!---在这里显示上传的图片,这个插件采用的为异步上传-->
            </div>
        </div>
    </form>
</body>
</html>
View Code

 

后端代码:

     public ActionResult UploadIndex2()
        {
            return View();
        }
       
        [HttpPost]
        public ActionResult HandlerUpload2()
        {
            HttpPostedFileBase file = Request.Files["Filedata"];//获取文件数据.
            string fileName = Path.GetFileName(file.FileName);//获取文件名.
            string fileExt = Path.GetExtension(fileName);    //获取文件类型
            string fullDir = "";
            if (fileExt == ".jpg")
            {
                string dir = "/UploadImage/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "/";
                Directory.CreateDirectory(Path.GetDirectoryName(Server.MapPath(dir)));//如果没有文件目录,创建.
                fullDir = dir + OnLineBooks.App.Common.WebCommon.GetStreamMD5(file.InputStream) + fileExt;//构建了一个完整路径,并且以文件流的MD5值作为文件的名称,解决了文件名称重名问题。
                file.SaveAs(Server.MapPath(fullDir));//文件保存                   
            }
            return Content(fullDir);//返回图片路径
        }

   

SWFUpload文件下载链接:http://pan.baidu.com/s/1c2xIf5Y 密码:wphd

 上面提到了图片上传,接下来小编带大家实现图像截取,先上图:

文件上传之——用SWF插件实现文件异步上传和头像截取

前台实现:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>UploadIndex3</title>
    <link href="~/Content/themes/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" />
    <script src="~/SWFUpload/swfupload.js" type="text/javascript"></script>
    <script src="~/SWFUpload/handlers.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/SWFUpload/jquery-ui-1.8.2.custom.min.js"></script>
    @*<script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>*@
    <script type="text/javascript">
    var swfu;
    window.onload = function () {
        swfu = new SWFUpload({
            // Backend Settings
            upload_url: "@Url.Action("Cut_upload", "Home")?action=up",
            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: showData,
            upload_complete_handler: uploadComplete,

            // Button settings
            button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png",
            button_placeholder_id: "spanButtonPlaceholder",
            button_width: 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
        });
    }
        //上传成功以后执行该方法.
        var data;
    function showData(file, serverData) {
        //一:创建一个DIV,通过该DIV确定出要截取大小与范围.(实现DIV的拖动与调整大小.)
        //首先将上传成功的图像作为divContent的背景图像.
         data = serverData.split(':');
        if (data[0] == "ok") {
            //设置图片的高度与宽度,注意单位.px
            $("#divContent").css("backgroundImage", "url(" + data[1] + ")").css("width", data[2] + "px").css("height", data[3] + "px");
        }
    }
    //拖动红色DIV并且可以调整大小.
    $(function () {
        $("#divCut").resizable({
            containment: "#divContent"
        }).draggable({ containment: "parent" });      //设置拖动  
        $("#btnCut").click(function () {
            CutImage();//截取头像
        });
    });
    function CutImage() {
        //offset():获取元素的绝对坐标 top:纵坐标
        var y = $("#divCut").offset().top - $("#divContent").offset().top;//纵坐标
        var x = $("#divCut").offset().left - $("#divContent").offset().left;
        var width = $("#divCut").width(); //宽度.
        var height = $("#divCut").height();
        //将上面的数据发送到服务端.
        $.post("@Url.Action("Cut_upload", "Home")", { "action": "cut", "x": parseInt(x), "y": parseInt(y), "width": parseInt(width), "height": parseInt(height), "imgUrl": data[1] }, function (data) {
            $("#imgUrl").attr("src", data);
        })
      

    }

</script>

</head>
<body>
    <form id="form1">
        <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>
            <div id="divContent" style="width:300px; height:300px">
                <div id="divCut" style="width:100px; height:100px; border:1px solid red"></div>
            </div>
            <input type="button" value="头像截取" id="btnCut" />
            <img id="imgUrl" />
        </div>
    </form>
</body>
</html>

后台实现:

    /// <summary>
        /// 截取图像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Cut_upload()
        {
            string action = Request["action"];
            if (action == "up")//上传
            {
                HttpPostedFileBase file = Request.Files["Filedata"];//获取文件数据.
                //获取文件名.
                string fileName = Path.GetFileName(file.FileName);
                //获取文件类型
                string fileExt = Path.GetExtension(fileName);
                if (fileExt == ".jpg")
                {
                    //获取上传的图片的流(文件内容),创建一个Image.所以Image的高度与宽度实际上就是上传图片的高度与宽度.
                    using (Image img = Image.FromStream(file.InputStream))
                    {
                        file.SaveAs(Server.MapPath("/UploadImage/" + fileName));                      
                        return Content("ok:/UploadImage/" + fileName + ":" + img.Width + ":" + img.Height);
                    }
                }
            }
            else if (action == "cut")//头像截取
            {
                //1:接收截取头像范围的数据
                int x = Convert.ToInt32(Request.Form["x"]);
                int y = Convert.ToInt32(Request.Form["y"]);
                int width = Convert.ToInt32(Request.Form["width"]);
                int height = Convert.ToInt32(Request.Form["height"]);
                string imgUrl = Request.Form["imgUrl"];
                //2:创建画布,然后将指定范围的图像画到画布上,最后保存画布.
                using (Bitmap map = new Bitmap(width, height))//画布的大小与截取的图像大小一致
                {
                    //为画布创建了一个画笔.
                    using (Graphics g = Graphics.FromImage(map))
                    {
                        //为上传成功的头像创建一个Image
                        using (Image img = Image.FromFile(Server.MapPath(imgUrl)))
                        {//将图像画到画布上.
                            //第一参数:表示对哪张图片进行操作.
                            //二:画多么大
                            //三:画哪一部分.
                            g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
                            string imgName = Guid.NewGuid().ToString().Substring(0, 8);
                            map.Save(Server.MapPath("/UploadImage/" + imgName + ".jpg"));//将Bitmap保存成图片文件                            
                            return Content("/UploadImage/" + imgName + ".jpg");
                        }
                    }
                }
            }
            return Content("");
        }

zj。。。