学习篇:文件MD5加密和无刷新上传图片

1.计算文件的MD5值。

因为网站有个上传文件的功能,为了防止重复上传相同文件,所以对文件进行MD5处理,作为文件的名称来存放。

        public static String GetStreamMD5(Stream stream)
        {
            string strResult = "";
            string strHashData = "";
            byte[] arrbytHashValue;
            System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
                new System.Security.Cryptography.MD5CryptoServiceProvider();
            arrbytHashValue = oMD5Hasher.ComputeHash(stream); //计算指定Stream 对象的哈希值
            //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
            strHashData = System.BitConverter.ToString(arrbytHashValue);
            //替换-
            strHashData = strHashData.Replace("-", "");
            strResult = strHashData;
            return strResult;
        }

2.无刷新上传图片,这里用到了一个Flash组件:SWFUpload。关于SWFUpload介绍:http://blog.endlesscode.com/2010/03/26/swfupload%E6%B5%85%E6%9E%90/   

一个简单的上传图片加显示效果的demo

SWFUpload-JS部分
 <script src="../SWFUpload/swfupload.js" type="text/javascript"></script>
    <script src="../SWFUpload/handlers.js" type="text/javascript"></script>
    <script type="text/javascript">
        var swfu;
        window.onload = function () {
            swfu = new SWFUpload({
                // Backend Settings
                upload_url: "../ashx/upload.ashx",
                post_params: {
                    "ASPSESSID": "<%=Session.SessionID %>"
                },

                // File Upload Settings
                file_size_limit: "2 MB",
                file_types: "*.jpg",
                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: showMsg,
                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
            });
        }

        function showMsg(file, serverData) {
            //alert(serverData);
            var data = serverData.split(":");
            if (data[0] == "ok") {
            
                document.getElementById("imgok").src = data[1];
            }
        }
    </script>
HTML部分
    <form id="form1" runat="server">
    <div id="swfu_container" style="margin: 0px 10px;">
        <div>
            <span id="spanButtonPlaceholder"></span>
        </div>
        <div id="divFileProgressContainer" style="height: 75px;">
        </div>
        <img id="imgok" />
    </div>
    </form>
upload.ashx 一般处理程序部分
context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            HttpPostedFile file = context.Request.Files["Filedata"];
            string fileName = Path.GetFileName(file.FileName);
            string fileExtention = Path.GetExtension(file.FileName);

            if (fileExtention == ".jpg")
            {
                string savePath = "/FileUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                //************************
                Directory.CreateDirectory(Path.GetDirectoryName(context.Server.MapPath(savePath)));

                string fullPath = savePath + Common.Common.GetStreamMD5(file.InputStream) + fileExtention;
                file.SaveAs(context.Server.MapPath(fullPath));
                context.Response.Write("ok:" + fullPath);

            }
            else
            {
                throw new Exception("文件类型有错~!");
            }

以上代码,可以实现一个简单的 上传图片加显示图片的效果。

高手莫拍砖~~.

 

posted @ 2012-10-19 23:50  2月18号  阅读(1142)  评论(0编辑  收藏  举报