标签:批量上传图片
C#批量上传图片篇:关于批量上传图片篇:主要讲解理清业务思路:
TODO:
1,采用地区控件,批量上传图片
2,两种方式生成动态数据(这里采用服务器端应用程序生成数据)
讲解篇:1,服务端aspx2,地区控件js与前端javascript3,服务端后台返回数据(这里采用服务器端程序:aspx.cs)
1,服务端aspx
1,地区控件aspx
<%@ Register TagPrefix="uc1" TagName="uc_btnSelectArea" Src="~/UserControl/uc_btnSelectArea.ascx" %> <tr> <td align="right" nowrap width="10%"> 附件上传: </td> <td align="left" width="90%" colspan="3"> <uc2:UC_SWFUpload ID="UC_SWFUpload1" runat="server" FileSizeLimit="10" FileTypes="*.jpg;*.png;*.bmp;*.flv;" /> </td> </tr>
1,handler.js
function fileQueueError(file, errorCode, message) { try { var imageName = "error.gif"; var errorName = ""; if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {//edit by xhm 2011-11-23 errorName = "尝试上传的文件超过限制."; } if (errorName !== "") { $.messager.alert('信息', errorName, 'info'); return; } switch (errorCode) { case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: imageName = "zerobyte.gif"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: imageName = "toobig.gif"; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: default: $.messager.alert('信息', message, 'info'); break; } addImage("/SWFUpload/images/" + imageName, file); } catch (ex) { this.debug(ex); } } var filesQueuedNum = 0; function fileDialogComplete(numFilesSelected, numFilesQueued) { filesQueuedNum += numFilesQueued; } function fileQueued(file) { var photoFile = { ClientID: file.id, ShowName: file.name, FileType: file.type }; AddPhotoDiv(photoFile, 1, false); } //添加图片显示样式div //参数file 文件对象 {id,name} //参数type 1 上传图片 2 加载图片 //参数IsExists 服务器文件是否存在 function AddPhotoDiv(file, type, IsExists) { var ID = IsExists ? file.ServerID : file.ClientID; $("#thumbnails").append("<div id='" + ID + "_div' class='fileDiv'>"); $("#" + ID + "_div").append("<a id='" + ID + "_link'><div class='photoDiv' title='" + ID + "' id='" + ID + "_photo'></div></a>"); $("#" + ID + "_div").append("<div id='" + ID + "_progressBox' class='progressBox' ></div>"); if (type == 1) { $("#" + ID + "_progressBox").append("<div class='progressLoad' id='" + ID + "_pro' ></div>"); } else { $("#" + ID + "_progressBox").append("<div class='progressLoaded' id='" + ID + "_pro' ></div>"); } $("#" + ID + "_div").append("<div id='" + ID + "_BeforeUpload' class='divnr-auto-photo' title='" + file.ShowName + "'></div>"); $("#" + ID + "_BeforeUpload").append("<input type='checkbox' id='" + ID + "' name='photo_Checkbox1' /> " + file.ShowName); } function uploadProgress(file, bytesLoaded) { try { var percent = Math.ceil((bytesLoaded / file.size) * 100); var progress = new FileProgress(file, file.id + "_pro"); progress.setProgress(percent); if (percent === 100) { //progress.setStatus("Creating thumbnail..."); progress.toggleCancel(false, this); } else { progress.setStatus(percent); progress.toggleCancel(true, this); } } catch (ex) { this.debug(ex); } } function uploadError(file, errorCode, message) { var imageName = "error.gif"; var progress; try { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Cancelled"); progress.toggleCancel(false); } catch (ex1) { this.debug(ex1); } break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Stopped"); progress.toggleCancel(true); } catch (ex2) { this.debug(ex2); } case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: imageName = "uploadlimit.gif"; break; default: $.messager.alert('信息', message, 'info'); break; } addImage("/SWFUpload/images/" + imageName, file); } catch (ex3) { this.debug(ex3); } } //添加Image图片 //scr 文件路径 //file 文件对象 {id,name,type} //IsFirst 是否第一次添加 function addImage(src, file, IsFirst) { $("#" + file.ClientID + "_photo").css("background", "url(" + src + ") center no-repeat "); $("#" + file.ClientID + "_photo").css("margin-left", "4px") $("#" + file.ClientID).attr("title", file.ServerID); if (file.State == 3) photoFiles.push(file); } //添加Image图片 //file 文件对象 {id,name,type} function addLink(file) { $("#" + file.ClientID + "_link").attr("href", "/pages/fileView.aspx?url=" + file.Path + file.SystemName); $("#" + file.ClientID + "_link").attr("target", "_blank"); //$("#" + file.ClientID + "_link").css("margin-left", "4px") } /* ****************************************** * FileProgress Object * Control object for displaying file info * ****************************************** */ function FileProgress(file, targetID) { this.fileProgressWrapper = $("#" + file.id + "_pro"); } FileProgress.prototype.setProgress = function (percentage) { this.fileProgressWrapper.css("width", percentage + "%"); }; FileProgress.prototype.setComplete = function () { // this.fileProgressElement.style.width = ""; }; FileProgress.prototype.setError = function () { // this.fileProgressElement.style.width = ""; }; FileProgress.prototype.setCancelled = function () { // this.fileProgressElement.style.width = ""; }; FileProgress.prototype.setStatus = function (status) { // this.fileProgressElement.childNodes[2].innerHTML = status; }; FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) { // this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden"; // if (swfuploadInstance) { // var fileID = this.fileProgressID; // this.fileProgressElement.childNodes[0].onclick = function () { // swfuploadInstance.cancelUpload(fileID); // return false; // }; // } }; function LoadFiles(files) { photoFiles = files; //把初始化加载服务器的文件集合,放入js对象中。 $.each(files, function (i, item) { AddPhotoDiv(item, 2, true); addImage(item.ThumbnailPath, item); addLink(item); }); }
2,json2.js
/* http://www.JSON.org/json2.js 2010-03-20 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ' '), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
/** * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com * * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ * * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz閚 and Mammon Media and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * */ /* ******************* */ /* Constructor & Init */ /* ******************* */ var SWFUpload; if (SWFUpload == undefined) { SWFUpload = function (settings) { this.initSWFUpload(settings); }; } SWFUpload.prototype.initSWFUpload = function (settings) { try { this.customSettings = {}; // A container where developers can place their own settings associated with this instance. this.settings = settings; this.eventQueue = []; this.movieName = "SWFUpload_" + SWFUpload.movieCount++; this.movieElement = null; // Setup global control tracking SWFUpload.instances[this.movieName] = this; // Load the settings. Load the Flash movie. this.initSettings(); this.loadFlash(); this.displayDebugInfo(); } catch (ex) { delete SWFUpload.instances[this.movieName]; throw ex; } }; /* *************** */ /* Static Members */ /* *************** */ SWFUpload.instances = {}; SWFUpload.movieCount = 0; SWFUpload.version = "2.2.0 2009-03-25"; SWFUpload.QUEUE_ERROR = { QUEUE_LIMIT_EXCEEDED : -100, FILE_EXCEEDS_SIZE_LIMIT : -110, ZERO_BYTE_FILE : -120, INVALID_FILETYPE : -130 }; SWFUpload.UPLOAD_ERROR = { HTTP_ERROR : -200, MISSING_UPLOAD_URL : -210, IO_ERROR : -220, SECURITY_ERROR : -230, UPLOAD_LIMIT_EXCEEDED : -240, UPLOAD_FAILED : -250, SPECIFIED_FILE_ID_NOT_FOUND : -260, FILE_VALIDATION_FAILED : -270, FILE_CANCELLED : -280, UPLOAD_STOPPED : -290 }; SWFUpload.FILE_STATUS = { QUEUED : -1, IN_PROGRESS : -2, ERROR : -3, COMPLETE : -4, CANCELLED : -5 }; SWFUpload.BUTTON_ACTION = { SELECT_FILE : -100, SELECT_FILES : -110, START_UPLOAD : -120 }; SWFUpload.CURSOR = { ARROW : -1, HAND : -2 }; SWFUpload.WINDOW_MODE = { WINDOW : "window", TRANSPARENT : "transparent", OPAQUE : "opaque" }; // Private: takes a URL, determines if it is relative and converts to an absolute URL // using the current site. Only processes the URL if it can, otherwise returns the URL untouched SWFUpload.completeURL = function(url) { if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) { return url; } var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : ""); var indexSlash = window.location.pathname.lastIndexOf("/"); if (indexSlash <= 0) { path = "/"; } else { path = window.location.pathname.substr(0, indexSlash) + "/"; } return /*currentURL +*/ path + url; }; /* ******************** */ /* Instance Members */ /* ******************** */ // Private: initSettings ensures that all the // settings are set, getting a default value if one was not assigned. SWFUpload.prototype.initSettings = function () { this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // Upload backend settings this.ensureDefault("upload_url", ""); this.ensureDefault("preserve_relative_urls", false); this.ensureDefault("file_post_name", "Filedata"); this.ensureDefault("post_params", {}); this.ensureDefault("use_query_string", false); this.ensureDefault("requeue_on_error", false); this.ensureDefault("http_success", []); this.ensureDefault("assume_success_timeout", 0); // File Settings this.ensureDefault("file_types", "*.*"); this.ensureDefault("file_types_description", "All Files"); this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited" this.ensureDefault("file_upload_limit", 0); this.ensureDefault("file_queue_limit", 0); // Flash Settings this.ensureDefault("flash_url", "swfupload.swf"); this.ensureDefault("prevent_swf_caching", true); // Button Settings this.ensureDefault("button_image_url", ""); this.ensureDefault("button_width", 1); this.ensureDefault("button_height", 1); this.ensureDefault("button_text", ""); this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;"); this.ensureDefault("button_text_top_padding", 0); this.ensureDefault("button_text_left_padding", 0); this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES); this.ensureDefault("button_disabled", false); this.ensureDefault("button_placeholder_id", ""); this.ensureDefault("button_placeholder", null); this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW); this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW); // Debug Settings this.ensureDefault("debug", false); this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API // Event Handlers this.settings.return_upload_start_handler = this.returnUploadStart; this.ensureDefault("swfupload_loaded_handler", null); this.ensureDefault("file_dialog_start_handler", null); this.ensureDefault("file_queued_handler", null); this.ensureDefault("file_queue_error_handler", null); this.ensureDefault("file_dialog_complete_handler", null); this.ensureDefault("upload_start_handler", null); this.ensureDefault("upload_progress_handler", null); this.ensureDefault("upload_error_handler", null); this.ensureDefault("upload_success_handler", null); this.ensureDefault("upload_complete_handler", null); this.ensureDefault("debug_handler", this.debugMessage); this.ensureDefault("custom_settings", {}); // Other settings this.customSettings = this.settings.custom_settings; // Update the flash url if needed if (!!this.settings.prevent_swf_caching) { this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime(); } if (!this.settings.preserve_relative_urls) { //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url); this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url); } delete this.ensureDefault; }; // Private: loadFlash replaces the button_placeholder element with the flash movie. SWFUpload.prototype.loadFlash = function () { var targetElement, tempParent; // Make sure an element with the ID we are going to use doesn't already exist if (document.getElementById(this.movieName) !== null) { throw "ID " + this.movieName + " is already in use. The Flash Object could not be added"; } // Get the element where we will be placing the flash movie targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder; if (targetElement == undefined) { throw "Could not find the placeholder element: " + this.settings.button_placeholder_id; } // Append the container and load the flash tempParent = document.createElement("div"); tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers) targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement); // Fix IE Flash/Form bug if (window[this.movieName] == undefined) { window[this.movieName] = this.getMovieElement(); } }; // Private: getFlashHTML generates the object tag needed to embed the flash in to the document SWFUpload.prototype.getFlashHTML = function () { // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">', '<param name="wmode" value="transparent" />', '<param name="movie" value="', this.settings.flash_url, '" />', '<param name="quality" value="high" />', '<param name="menu" value="false" />', '<param name="allowScriptAccess" value="always" />', '<param name="flashvars" value="' + this.getFlashVars() + '" />', '</object>'].join(""); }; // Private: getFlashVars builds the parameter string that will be passed // to flash in the flashvars param. SWFUpload.prototype.getFlashVars = function () { // Build a string from the post param object var paramString = this.buildParamString(); var httpSuccessString = this.settings.http_success.join(","); // Build the parameter string return ["movieName=", encodeURIComponent(this.movieName), "&uploadURL=", encodeURIComponent(this.settings.upload_url), "&useQueryString=", encodeURIComponent(this.settings.use_query_string), "&requeueOnError=", encodeURIComponent(this.settings.requeue_on_error), "&httpSuccess=", encodeURIComponent(httpSuccessString), "&assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout), "¶ms=", encodeURIComponent(paramString), "&filePostName=", encodeURIComponent(this.settings.file_post_name), "&fileTypes=", encodeURIComponent(this.settings.file_types), "&fileTypesDescription=", encodeURIComponent(this.settings.file_types_description), "&fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit), "&fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit), "&fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit), "&debugEnabled=", encodeURIComponent(this.settings.debug_enabled), "&buttonImageURL=", encodeURIComponent(this.settings.button_image_url), "&buttonWidth=", encodeURIComponent(this.settings.button_width), "&buttonHeight=", encodeURIComponent(this.settings.button_height), "&buttonText=", encodeURIComponent(this.settings.button_text), "&buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding), "&buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding), "&buttonTextStyle=", encodeURIComponent(this.settings.button_text_style), "&buttonAction=", encodeURIComponent(this.settings.button_action), "&buttonDisabled=", encodeURIComponent(this.settings.button_disabled), "&buttonCursor=", encodeURIComponent(this.settings.button_cursor) ].join(""); }; // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload // The element is cached after the first lookup SWFUpload.prototype.getMovieElement = function () { if (this.movieElement == undefined) { this.movieElement = document.getElementById(this.movieName); } if (this.movieElement === null) { throw "Could not find Flash element"; } return this.movieElement; }; // Private: buildParamString takes the name/value pairs in the post_params setting object // and joins them up in to a string formatted "name=value&name=value" SWFUpload.prototype.buildParamString = function () { var postParams = this.settings.post_params; var paramStringPairs = []; if (typeof(postParams) === "object") { for (var name in postParams) { if (postParams.hasOwnProperty(name)) { paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString())); } } } return paramStringPairs.join("&"); }; // Public: Used to remove a SWFUpload instance from the page. This method strives to remove // all references to the SWF, and other objects so memory is properly freed. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state. // Credits: Major improvements provided by steffen SWFUpload.prototype.destroy = function () { try { // Make sure Flash is done before we try to remove it this.cancelUpload(null, false); // Remove the SWFUpload DOM nodes var movieElement = null; movieElement = this.getMovieElement(); if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround) for (var i in movieElement) { try { if (typeof(movieElement[i]) === "function") { movieElement[i] = null; } } catch (ex1) {} } // Remove the Movie Element from the page try { movieElement.parentNode.removeChild(movieElement); } catch (ex) {} } // Remove IE form fix reference window[this.movieName] = null; // Destroy other references SWFUpload.instances[this.movieName] = null; delete SWFUpload.instances[this.movieName]; this.movieElement = null; this.settings = null; this.customSettings = null; this.eventQueue = null; this.movieName = null; return true; } catch (ex2) { return false; } }; // Public: displayDebugInfo prints out settings and configuration // information about this SWFUpload instance. // This function (and any references to it) can be deleted when placing // SWFUpload in production. SWFUpload.prototype.displayDebugInfo = function () { this.debug( [ "---SWFUpload Instance Info---\n", "Version: ", SWFUpload.version, "\n", "Movie Name: ", this.movieName, "\n", "Settings:\n", "\t", "upload_url: ", this.settings.upload_url, "\n", "\t", "flash_url: ", this.settings.flash_url, "\n", "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n", "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n", "\t", "http_success: ", this.settings.http_success.join(", "), "\n", "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n", "\t", "file_post_name: ", this.settings.file_post_name, "\n", "\t", "post_params: ", this.settings.post_params.toString(), "\n", "\t", "file_types: ", this.settings.file_types, "\n", "\t", "file_types_description: ", this.settings.file_types_description, "\n", "\t", "file_size_limit: ", this.settings.file_size_limit, "\n", "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n", "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n", "\t", "debug: ", this.settings.debug.toString(), "\n", "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n", "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n", "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n", "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n", "\t", "button_width: ", this.settings.button_width.toString(), "\n", "\t", "button_height: ", this.settings.button_height.toString(), "\n", "\t", "button_text: ", this.settings.button_text.toString(), "\n", "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n", "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n", "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n", "\t", "button_action: ", this.settings.button_action.toString(), "\n", "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n", "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n", "Event Handlers:\n", "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n", "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n", "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n", "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n", "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n", "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n", "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n", "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n", "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n", "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n" ].join("") ); }; /* Note: addSetting and getSetting are no longer used by SWFUpload but are included the maintain v2 API compatibility */ // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used. SWFUpload.prototype.addSetting = function (name, value, default_value) { if (value == undefined) { return (this.settings[name] = default_value); } else { return (this.settings[name] = value); } }; // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found. SWFUpload.prototype.getSetting = function (name) { if (this.settings[name] != undefined) { return this.settings[name]; } return ""; }; // Private: callFlash handles function calls made to the Flash element. // Calls are made with a setTimeout for some functions to work around // bugs in the ExternalInterface library. SWFUpload.prototype.callFlash = function (functionName, argumentArray) { argumentArray = argumentArray || []; var movieElement = this.getMovieElement(); var returnValue, returnString; // Flash's method if calling ExternalInterface methods (code adapted from MooTools). try { returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>'); returnValue = eval(returnString); } catch (ex) { throw "Call to " + functionName + " failed"; } // Unescape file post param values if (returnValue != undefined && typeof returnValue.post === "object") { returnValue = this.unescapeFilePostParams(returnValue); } return returnValue; }; /* ***************************** -- Flash control methods -- Your UI should use these to operate SWFUpload ***************************** */ // WARNING: this function does not work in Flash Player 10 // Public: selectFile causes a File Selection Dialog window to appear. This // dialog only allows 1 file to be selected. SWFUpload.prototype.selectFile = function () { this.callFlash("SelectFile"); }; // WARNING: this function does not work in Flash Player 10 // Public: selectFiles causes a File Selection Dialog window to appear/ This // dialog allows the user to select any number of files // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around // for this bug. SWFUpload.prototype.selectFiles = function () { this.callFlash("SelectFiles"); }; // Public: startUpload starts uploading the first file in the queue unless // the optional parameter 'fileID' specifies the ID SWFUpload.prototype.startUpload = function (fileID) { this.callFlash("StartUpload", [fileID]); }; // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) { if (triggerErrorEvent !== false) { triggerErrorEvent = true; } this.callFlash("CancelUpload", [fileID, triggerErrorEvent]); }; // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue. // If nothing is currently uploading then nothing happens. SWFUpload.prototype.stopUpload = function () { this.callFlash("StopUpload"); }; /* ************************ * Settings methods * These methods change the SWFUpload settings. * SWFUpload settings should not be changed directly on the settings object * since many of the settings need to be passed to Flash in order to take * effect. * *********************** */ // Public: getStats gets the file statistics object. SWFUpload.prototype.getStats = function () { return this.callFlash("GetStats"); }; // Public: setStats changes the SWFUpload statistics. You shouldn't need to // change the statistics but you can. Changing the statistics does not // affect SWFUpload accept for the successful_uploads count which is used // by the upload_limit setting to determine how many files the user may upload. SWFUpload.prototype.setStats = function (statsObject) { this.callFlash("SetStats", [statsObject]); }; // Public: getFile retrieves a File object by ID or Index. If the file is // not found then 'null' is returned. SWFUpload.prototype.getFile = function (fileID) { if (typeof(fileID) === "number") { return this.callFlash("GetFileByIndex", [fileID]); } else { return this.callFlash("GetFile", [fileID]); } }; // Public: addFileParam sets a name/value pair that will be posted with the // file specified by the Files ID. If the name already exists then the // exiting value will be overwritten. SWFUpload.prototype.addFileParam = function (fileID, name, value) { return this.callFlash("AddFileParam", [fileID, name, value]); }; // Public: removeFileParam removes a previously set (by addFileParam) name/value // pair from the specified file. SWFUpload.prototype.removeFileParam = function (fileID, name) { this.callFlash("RemoveFileParam", [fileID, name]); }; // Public: setUploadUrl changes the upload_url setting. SWFUpload.prototype.setUploadURL = function (url) { this.settings.upload_url = url.toString(); this.callFlash("SetUploadURL", [url]); }; // Public: setPostParams changes the post_params setting SWFUpload.prototype.setPostParams = function (paramsObject) { this.settings.post_params = paramsObject; this.callFlash("SetPostParams", [paramsObject]); }; // Public: addPostParam adds post name/value pair. Each name can have only one value. SWFUpload.prototype.addPostParam = function (name, value) { this.settings.post_params[name] = value; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: removePostParam deletes post name/value pair. SWFUpload.prototype.removePostParam = function (name) { delete this.settings.post_params[name]; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: setFileTypes changes the file_types setting and the file_types_description setting SWFUpload.prototype.setFileTypes = function (types, description) { this.settings.file_types = types; this.settings.file_types_description = description; this.callFlash("SetFileTypes", [types, description]); }; // Public: setFileSizeLimit changes the file_size_limit setting SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) { this.settings.file_size_limit = fileSizeLimit; this.callFlash("SetFileSizeLimit", [fileSizeLimit]); }; // Public: setFileUploadLimit changes the file_upload_limit setting SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) { this.settings.file_upload_limit = fileUploadLimit; this.callFlash("SetFileUploadLimit", [fileUploadLimit]); }; // Public: setFileQueueLimit changes the file_queue_limit setting SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) { this.settings.file_queue_limit = fileQueueLimit; this.callFlash("SetFileQueueLimit", [fileQueueLimit]); }; // Public: setFilePostName changes the file_post_name setting SWFUpload.prototype.setFilePostName = function (filePostName) { this.settings.file_post_name = filePostName; this.callFlash("SetFilePostName", [filePostName]); }; // Public: setUseQueryString changes the use_query_string setting SWFUpload.prototype.setUseQueryString = function (useQueryString) { this.settings.use_query_string = useQueryString; this.callFlash("SetUseQueryString", [useQueryString]); }; // Public: setRequeueOnError changes the requeue_on_error setting SWFUpload.prototype.setRequeueOnError = function (requeueOnError) { this.settings.requeue_on_error = requeueOnError; this.callFlash("SetRequeueOnError", [requeueOnError]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) { if (typeof http_status_codes === "string") { http_status_codes = http_status_codes.replace(" ", "").split(","); } this.settings.http_success = http_status_codes; this.callFlash("SetHTTPSuccess", [http_status_codes]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) { this.settings.assume_success_timeout = timeout_seconds; this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]); }; // Public: setDebugEnabled changes the debug_enabled setting SWFUpload.prototype.setDebugEnabled = function (debugEnabled) { this.settings.debug_enabled = debugEnabled; this.callFlash("SetDebugEnabled", [debugEnabled]); }; // Public: setButtonImageURL loads a button image sprite SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) { if (buttonImageURL == undefined) { buttonImageURL = ""; } this.settings.button_image_url = buttonImageURL; this.callFlash("SetButtonImageURL", [buttonImageURL]); }; // Public: setButtonDimensions resizes the Flash Movie and button SWFUpload.prototype.setButtonDimensions = function (width, height) { this.settings.button_width = width; this.settings.button_height = height; var movie = this.getMovieElement(); if (movie != undefined) { movie.style.width = width + "px"; movie.style.height = height + "px"; } this.callFlash("SetButtonDimensions", [width, height]); }; // Public: setButtonText Changes the text overlaid on the button SWFUpload.prototype.setButtonText = function (html) { this.settings.button_text = html; this.callFlash("SetButtonText", [html]); }; // Public: setButtonTextPadding changes the top and left padding of the text overlay SWFUpload.prototype.setButtonTextPadding = function (left, top) { this.settings.button_text_top_padding = top; this.settings.button_text_left_padding = left; this.callFlash("SetButtonTextPadding", [left, top]); }; // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button SWFUpload.prototype.setButtonTextStyle = function (css) { this.settings.button_text_style = css; this.callFlash("SetButtonTextStyle", [css]); }; // Public: setButtonDisabled disables/enables the button SWFUpload.prototype.setButtonDisabled = function (isDisabled) { this.settings.button_disabled = isDisabled; this.callFlash("SetButtonDisabled", [isDisabled]); }; // Public: setButtonAction sets the action that occurs when the button is clicked SWFUpload.prototype.setButtonAction = function (buttonAction) { this.settings.button_action = buttonAction; this.callFlash("SetButtonAction", [buttonAction]); }; // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button SWFUpload.prototype.setButtonCursor = function (cursor) { this.settings.button_cursor = cursor; this.callFlash("SetButtonCursor", [cursor]); }; /* ******************************* Flash Event Interfaces These functions are used by Flash to trigger the various events. All these functions a Private. Because the ExternalInterface library is buggy the event calls are added to a queue and the queue then executed by a setTimeout. This ensures that events are executed in a determinate order and that the ExternalInterface bugs are avoided. ******************************* */ SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) { // Warning: Don't call this.debug inside here or you'll create an infinite loop if (argumentArray == undefined) { argumentArray = []; } else if (!(argumentArray instanceof Array)) { argumentArray = [argumentArray]; } var self = this; if (typeof this.settings[handlerName] === "function") { // Queue the event this.eventQueue.push(function () { this.settings[handlerName].apply(this, argumentArray); }); // Execute the next queued event setTimeout(function () { self.executeNextEvent(); }, 0); } else if (this.settings[handlerName] !== null) { throw "Event handler " + handlerName + " is unknown or is not a function"; } }; // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout // we must queue them in order to garentee that they are executed in order. SWFUpload.prototype.executeNextEvent = function () { // Warning: Don't call this.debug inside here or you'll create an infinite loop var f = this.eventQueue ? this.eventQueue.shift() : null; if (typeof(f) === "function") { f.apply(this); } }; // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have // properties that contain characters that are not valid for JavaScript identifiers. To work around this // the Flash Component escapes the parameter names and we must unescape again before passing them along. SWFUpload.prototype.unescapeFilePostParams = function (file) { var reg = /[$]([0-9a-f]{4})/i; var unescapedPost = {}; var uk; if (file != undefined) { for (var k in file.post) { if (file.post.hasOwnProperty(k)) { uk = k; var match; while ((match = reg.exec(uk)) !== null) { uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16))); } unescapedPost[uk] = file.post[k]; } } file.post = unescapedPost; } return file; }; // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working) SWFUpload.prototype.testExternalInterface = function () { try { return this.callFlash("TestExternalInterface"); } catch (ex) { return false; } }; // Private: This event is called by Flash when it has finished loading. Don't modify this. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded. SWFUpload.prototype.flashReady = function () { // Check that the movie element is loaded correctly with its ExternalInterface methods defined var movieElement = this.getMovieElement(); if (!movieElement) { this.debug("Flash called back ready but the flash movie can't be found."); return; } this.cleanUp(movieElement); this.queueEvent("swfupload_loaded_handler"); }; // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE. // This function is called by Flash each time the ExternalInterface functions are created. SWFUpload.prototype.cleanUp = function (movieElement) { // Pro-actively unhook all the Flash functions try { if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)"); for (var key in movieElement) { try { if (typeof(movieElement[key]) === "function") { movieElement[key] = null; } } catch (ex) { } } } } catch (ex1) { } // Fix Flashes own cleanup code so if the SWFMovie was removed from the page // it doesn't display errors. window["__flash__removeCallback"] = function (instance, name) { try { if (instance) { instance[name] = null; } } catch (flashEx) { } }; }; /* This is a chance to do something before the browse window opens */ SWFUpload.prototype.fileDialogStart = function () { this.queueEvent("file_dialog_start_handler"); }; /* Called when a file is successfully added to the queue. */ SWFUpload.prototype.fileQueued = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queued_handler", file); }; /* Handle errors that occur when an attempt to queue a file fails. */ SWFUpload.prototype.fileQueueError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queue_error_handler", [file, errorCode, message]); }; /* Called after the file dialog has closed and the selected files have been queued. You could call startUpload here if you want the queued files to begin uploading immediately. */ SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) { this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]); }; SWFUpload.prototype.uploadStart = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("return_upload_start_handler", file); }; SWFUpload.prototype.returnUploadStart = function (file) { var returnValue; if (typeof this.settings.upload_start_handler === "function") { file = this.unescapeFilePostParams(file); returnValue = this.settings.upload_start_handler.call(this, file); } else if (this.settings.upload_start_handler != undefined) { throw "upload_start_handler must be a function"; } // Convert undefined to true so if nothing is returned from the upload_start_handler it is // interpretted as 'true'. if (returnValue === undefined) { returnValue = true; } returnValue = !!returnValue; this.callFlash("ReturnUploadStart", [returnValue]); }; SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]); }; SWFUpload.prototype.uploadError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_error_handler", [file, errorCode, message]); }; SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_success_handler", [file, serverData, responseReceived]); }; SWFUpload.prototype.uploadComplete = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_complete_handler", file); }; /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the internal debug console. You can override this event and have messages written where you want. */ SWFUpload.prototype.debug = function (message) { this.queueEvent("debug_handler", message); }; /* ********************************** Debug Console The debug console is a self contained, in page location for debug message to be sent. The Debug Console adds itself to the body if necessary. The console is automatically scrolled as messages appear. If you are using your own debug handler or when you deploy to production and have debug disabled you can remove these functions to reduce the file size and complexity. ********************************** */ // Private: debugMessage is the default debug_handler. If you want to print debug messages // call the debug() function. When overriding the function your own function should // check to see if the debug setting is true before outputting debug information. SWFUpload.prototype.debugMessage = function (message) { if (this.settings.debug) { var exceptionMessage, exceptionValues = []; // Check for an exception object and print it nicely if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") { for (var key in message) { if (message.hasOwnProperty(key)) { exceptionValues.push(key + ": " + message[key]); } } exceptionMessage = exceptionValues.join("\n") || ""; exceptionValues = exceptionMessage.split("\n"); exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: "); SWFUpload.Console.writeLine(exceptionMessage); } else { SWFUpload.Console.writeLine(message); } } }; SWFUpload.Console = {}; SWFUpload.Console.writeLine = function (message) { var console, documentForm; try { console = document.getElementById("SWFUpload_Console"); if (!console) { documentForm = document.createElement("form"); document.getElementsByTagName("body")[0].appendChild(documentForm); console = document.createElement("textarea"); console.id = "SWFUpload_Console"; console.style.fontFamily = "monospace"; console.setAttribute("wrap", "off"); console.wrap = "off"; console.style.overflow = "auto"; console.style.width = "700px"; console.style.height = "350px"; console.style.margin = "5px"; documentForm.appendChild(console); } console.value += message + "\n"; console.scrollTop = console.scrollHeight - console.clientHeight; } catch (ex) { alert("Exception: " + ex.name + " Message: " + ex.message); } };
4,swfupload.css
.btnhide { display: none; } .btnDiv { float: left; padding-right: 4px; z-index: -1; } .divnr-auto-photo { margin: 0 auto; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; width: auto; _width: 100px; font-size: 12px; text-align: left; padding-left: 4px; padding-right: 4px; padding-bottom: 4px; } .divnr-auto-photo input { vertical-align: middle; } .progressBox { width: 102px; height: 6px; _height: 2px; border: 1px solid #6593CF; margin: 4px auto; font-size: 5px; } .progressLoad { background: url(images/loadt05.gif) repeat-x left; width: 0px; height: 6px; _height: 2px; font-size: 5px; } .progressLoaded { background: url(images/loadt05.gif) repeat-x left; width: 100%; height: 6px; _height: 2px; font-size: 5px; } .fileDiv { margin: 6px; padding-top: 4px; padding-right: 2px; padding-left: 2px; width: 110px; height: 140px; float: left; } .photoDiv { margin: 0px; padding: 0px; width: 108px; height: 108px; text-align: center; vertical-align: middle; padding-left: 0px; background: url(images/null.png) center no-repeat; margin-left: 2px; } .listUpload { margin: 0px 1px 0px 0px; padding: 0px; float: left; width: 100%; border: solid 1px; height: 180px; overflow-x: auto; }
5,UC_SWFUpload.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UC_SWFUpload.ascx.cs" Inherits="HMFW.Web.SWFUpload.UC_SWFUpload" %> <script src="<%=ResolveUrl("~/SWFUpload/swfupload/swfupload.js") %>" type="text/javascript"></script> <script src="<%=ResolveUrl("~/SWFUpload/js/handlers.js") %>" type="text/javascript"></script> <script src="<%=ResolveUrl("~/SWFUpload/js/json2.js") %>" type="text/javascript"></script> <link href="<%=ResolveUrl("~/SWFUpload/swfUpload.css") %>" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var swfu; window.onload = function () { swfu = new SWFUpload({ // Backend Settings upload_url: "<%=ResolveUrl("~/SWFUpload/Upload.ashx") %>", post_params: { "UploadPathAdd": "<%=UploadPathAdd %>", "BindsAreaCode": "<%=BindsAreaCode %>" }, // File Upload Settings file_size_limit: "<%=FileSizeLimit %> MB", file_types: "<%=FileTypes %>", file_types_description: "<%=ButtonText %>", file_upload_limit: "<%=FileUploadLimit %>", // 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. file_queue_error_handler: fileQueueError, file_queued_handler: fileQueued, file_dialog_complete_handler: fileDialogComplete, upload_progress_handler: uploadProgress, upload_error_handler: uploadError, upload_success_handler: uploadSuccess, upload_complete_handler: uploadComplete, // Button settings button_image_url: "<%=ResolveUrl("~/SWFUpload/images/btn001.png") %>", //XPButtonNoText_160x22.png button_placeholder_id: "spanButtonPlaceholder", button_width: 61, button_height: 22, button_text: '<%=ButtonText %>', //(最大2M) button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 1, button_text_left_padding: 5, // Flash Settings flash_url: "<%=ResolveUrl("~/SWFUpload/swfupload/swfupload.swf") %>", // Relative to this file custom_settings: { upload_target: "divFileProgressContainer" }, // Debug Settings debug: false }); } //上传 function OnUpload() { if (filesQueuedNum > 0){ // var Succount=0; // $.each(photoFiles, function (i, item) { // if (item.State == "1" || item.State == "0") { // ++Succount; // } // }); // if(Succount+filesQueuedNum>1) // { // $.messager.alert('错误', '只能上传一张照片!', 'info'); // } // else // { swfu.startUpload(); filesQueuedNum = 0; // } } else { $.messager.alert('错误', '请选择要上传的文件!', 'info'); } //alert("请选择要上传的文件!"); return false; } function ClearFile() { $("input[name*='photo_Checkbox']").each(function () { var photoFile = swfu.getFile(this.id); if (photoFile) {//正在上传 swfu.cancelUpload(this.id, false); } $("#" + this.id+ "_div").remove(); }); photoFiles = new Array(); } function OnDelete() { var values = new Array(); var count = 0; $("input[name*='photo_Checkbox']").each(function () { if (this.checked) { values.push(this.id); ++count; } }); if (count == 0) { $.messager.alert('错误', '请选择需要删除的文件!', 'info'); //alert("请选择需要删除的文件!"); return false; } else { $.messager.confirm('警告', '你确认要删除选中的文件吗?', function (r) { if (r) { Delete(values); } }); // if (confirm("你确认要删除选中的文件吗?")) { // Delete(values); // } return false; } } var photoFiles = new Array(); //删除 function Delete(values) { var IsHaveDelete = false; //是否有需要删除的文件 for (var i = 0; i < values.length; i++) { var photoFile = swfu.getFile(values[i]); if (!photoFile) { var tmpID = $("#" + values[i]).attr("title"); var tmpFile = GetFileByServerID(tmpID); tmpFile.State = 2; //标记为删除 IsHaveDelete = true; } else { swfu.cancelUpload(values[i], false); } $("#" + values[i] + "_div").remove(); } if (IsHaveDelete) { $("#<%=hidDeleteFiles.ClientID %>").val(JSON.stringify(GetDeleteFiles())); $.ajax({ type: "POST", dataType: "text", url: "<%=ResolveUrl("~/SWFUpload/DeleteFiles.ashx") %>", data: { DeleteFiles: $.trim($("#<%=hidDeleteFiles.ClientID %>").val()) }, beforeSend: function () { }, complete: function () { }, success: function (result) { if (result == "1") { for (var i = 0; i < photoFiles.length; i++) { if (photoFiles[i].State == 2)//如果为标记为删除的 { photoFiles[i].State = 3; //标记为删除成功 } } } else { } }, error: function (XmlHttpRequest, textStatus, errorThrown) { $.messager.alert('错误', errorThrown, 'error'); } }); } } //根据文件ID获取文件信息 function GetFileByServerID(ServerID) { for (var i = 0; i < photoFiles.length; i++) { if (photoFiles[i].ServerID == ServerID) return photoFiles[i]; } } //获取删除文件集合 function GetDeleteFiles() { var DeleteFiles = new Array(); for (var i = 0; i < photoFiles.length; i++) { if (photoFiles[i].State == 2) { DeleteFiles.push(photoFiles[i]); } } return DeleteFiles; } //上传成功 function uploadSuccess(file, serverData) { try { var strPhotoFile = serverData; var tmpFile = eval('(' + strPhotoFile + ')'); tmpFile.ClientID = file.id; //addImage("thumbnail.ashx?id=" + tmpFile.ServerID, tmpFile, true); addImage(tmpFile.ThumbnailPath, tmpFile, true); addLink(tmpFile); var progress = new FileProgress(file, this.customSettings.upload_target); // progress.setStatus("Thumbnail Created."); progress.toggleCancel(false); photoFiles.push(tmpFile); } catch (ex) { this.debug(ex); } } //获取上传文件集合 function GetUploadFiles() { var UploadFiles = new Array(); for (var i = 0; i < photoFiles.length; i++) { if (photoFiles[i].State == 0) { UploadFiles.push(photoFiles[i]); } } return UploadFiles; } function uploadComplete(file) { try { /* I want the next upload to continue automatically so I'll call startUpload here */ if (this.getStats().files_queued > 0) { this.startUpload(); } else { var progress = new FileProgress(file, this.customSettings.upload_target); progress.setComplete(); progress.toggleCancel(false); $("#<%=hidUploadFiles.ClientID %>").val(JSON.stringify(GetUploadFiles())); //UploadFiles Ajax for (var i = 0; i < photoFiles.length; i++) { if (photoFiles[i].State == 0) photoFiles[i].State = 1; } } } catch (ex) { this.debug(ex); } } </script> <div id="content"> <div id="swfu_container" style="margin: 0px 2px 0px 0px;"> <table id='divHead' width="100%" align="center" class="datagrid-toolbar" style="height: 30px;"> <tr> <td> <div style="height: 22px; margin-top: 2px; margin-left: 4px; vertical-align: middle;"> <div class="btnDiv"> <span id="spanButtonPlaceholder"></span> </div> <xhm:xhmButtionEasyUI ID="btnStart" runat="server" IconTypeSelected="up" OnClientClick="return OnUpload();">开始上传</xhm:xhmButtionEasyUI> <xhm:xhmButtionEasyUI ID="btnDelete" runat="server" IconTypeSelected="delete" OnClientClick="return OnDelete();">删除</xhm:xhmButtionEasyUI> <%--<asp:Button ID="btnDelete" runat="server" OnClientClick="OnDelete();return false;" TabIndex="0" Text="删除" class="btn04" />--%> </div> </td> </tr> </table> <div style="height: 200px; margin: 0px 2px 0px 0px;"> <div id="thumbnails" class="listUpload"> <asp:Literal ID="Literal1" runat="server"></asp:Literal> </div> </div> <div id="divFileProgressContainer" style="height: 0px;"> </div> </div> <asp:HiddenField ID="hidDeleteFiles" runat="server" /> <asp:HiddenField ID="hidUploadFiles" runat="server" /> </div>
6,UC_SWFUpload.ascx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.IO; using HMFW.Model; using HMFW.Web.App_Code; using System.ComponentModel; namespace HMFW.Web.SWFUpload { public partial class UC_SWFUpload : System.Web.UI.UserControl { protected override void OnInit(EventArgs e) { if (!IsPostBack && !IsLoadPhoto) { this.IsLoadPhoto = false; } base.OnInit(e); } private bool IsLoadPhoto = false; private StringBuilder javaScript = null; private void AppendJaveScript(string script) { if (javaScript == null) { javaScript = new StringBuilder(); javaScript.Append("$(document).ready(function() {"); } javaScript = javaScript.Replace("} ) ;", ""); javaScript.Append(script); javaScript.Append("} ) ;"); } private void LoadPhoto(List<FileModel> files) { this.IsLoadPhoto = true; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (var item in files) { string type = item.FileType; string path = item.Path + item.SystemName; string id = item.ServerID; bool IsExistThumb = false; string FileType = ImgHelper.GetExtentionFileName(path).ToLower(); if (ImgHelper.IsImageFile(FileType)) { //如果不存在缩略图,但是源文件存在,则重新生成源文件 if (File.Exists(Server.MapPath(item.ThumbnailPath)) && File.Exists(Server.MapPath(path))) { string thumbpath = path.Replace(type, string.Empty) + "_thumb" + type; path = Server.MapPath(path); using (FileStream fs = new FileStream(path, FileMode.Open)) { using (System.Drawing.Image original_image = System.Drawing.Image.FromStream(fs)) { //保存缩略图(物理路径参数) ImgHelper.CompressAsPath(original_image, new System.Drawing.Rectangle(0, 0, 100, 100), Server.MapPath(thumbpath)); item.ThumbnailPath = thumbpath; } } IsExistThumb = true; } } //为其他类型的文件的话缩略图不用生成 else { //文件类型不加点("txt"而不是".txt") string FileTypeName = FileType.Substring(1, FileType.Length - 1); item.ThumbnailPath = "~/SWFUpload/images/" + FileTypeName + ".png"; } item.State = 3; //加载状态 item.ClientID = item.ServerID; //缩略图问题--看看是否可以不需要动态生成缩略图 item.ThumbnailPath = ResolveUrl(item.ThumbnailPath); string strFile = JsonHelper.ModelToJsonString<FileModel>(item); AppendJaveScript("var file=" + strFile + ";"); if (IsExistThumb) { AppendJaveScript("AddPhotoDiv(file,2,true);"); //AppendJaveScript("addImage('thumbnail.ashx?id=" + item.ServerID + "',file);"); AppendJaveScript("addImage(file.ThumbnailPath,file);"); AppendJaveScript("addLink(file);"); } else { AppendJaveScript("AddPhotoDiv(file,2,false);"); AppendJaveScript("addImage('/SWFUpload/images/noFile.gif',file);"); } } this.Literal1.Text = sb.ToString(); } public void LoadPhotoList(List<FileModel> files) { LoadPhoto(files); if (javaScript != null) ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertinfo", javaScript.ToString(), true); } public void LoadPhotoList(List<FileModel> files, bool IsView) { LoadPhoto(files); //AppendJaveScript("$(\"div[id*='_progress']\").hide();"); //AppendJaveScript("$('#divHead').hide();"); //AppendJaveScript("$(\"input[name*='photo_Checkbox']\").hide();"); AppendJaveScript("$(\".fileDiv\").css(\"height\", \"122px\");"); AppendJaveScript("$(\".divnr-auto-photo\").css(\"text-align\", \"center\");"); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertinfo", javaScript.ToString(), true); } /// <summary> /// 在默认上传路径上后的文件夹 /// </summary> [Bindable(true)] [Description("默认上传路径之后的文件夹的名称"), Category("属性")] [DefaultValue("")] [Localizable(true)] public string UploadPathAdd { get { if (ViewState["UploadPathAdd"] == null) return ""; return ViewState["UploadPathAdd"].ToString(); } set { if (string.IsNullOrEmpty(value)) ViewState["UploadPathAdd"] = ""; ViewState["UploadPathAdd"] = value; } } /// <summary> /// SWF限制上传的个数,0不限制 /// </summary> [Bindable(true)] [Description("SWF限制上传的个数,0不限制"), Category("属性")] [DefaultValue("0")] [Localizable(true)] public string FileUploadLimit { get { if (ViewState["FileUploadLimit"] == null) return "0"; return ViewState["FileUploadLimit"].ToString(); } set { if (string.IsNullOrEmpty(value)) ViewState["FileUploadLimit"] = "0"; ViewState["FileUploadLimit"] = value; } } /// <summary> /// SWF限制上传的个数,0不限制 /// </summary> [Bindable(true)] [Description("上传文件的大小限制"), Category("属性")] [DefaultValue("2")] [Localizable(true)] public string FileSizeLimit { get { if (ViewState["FileSizeLimit"] == null) return "2"; return ViewState["FileSizeLimit"].ToString(); } set { if (string.IsNullOrEmpty(value)) ViewState["FileSizeLimit"] = "2"; ViewState["FileSizeLimit"] = value; } } /// <summary> /// 是否绑定地区编码 /// </summary> [Bindable(true)] [Description("是否绑定地区编码,在UploadPath后面加一个用户的地区编码"), Category("属性")] [DefaultValue(IsBindsAreaCode.False)] [Localizable(true)] public IsBindsAreaCode BindsAreaCode { get { if (ViewState["BindsAreaCode"] == null) return IsBindsAreaCode.False; return (IsBindsAreaCode)ViewState["BindsAreaCode"]; } set { ViewState["BindsAreaCode"] = value; } } public enum IsBindsAreaCode { True, False } /// <summary> /// 选择按钮的文字,默认为“选择文件” /// </summary> [Bindable(true)] [Description("选择按钮的文字,默认为“选择文件”"), Category("属性")] [DefaultValue("选择文件")] [Localizable(true)] public string ButtonText { get { if (ViewState["ButtonText"] == null) return "选择文件"; return ViewState["ButtonText"].ToString(); } set { ViewState["ButtonText"] = value; } } /// <summary> /// 上传文件的类型 /// </summary> [Bindable(true)] [Description("上传文件的类型默认为Config设置里面的,可以单独设置。格式为:*.jpg;*.png;*.bmp;*.doc;*.docx;*.txt;*.pdf;"), Category("属性")] [Localizable(true)] public string FileTypes { get { if (ViewState["FileTypes"] == null) return HMFW.Common.GlobalSettings.Instance.FileTypes; return ViewState["FileTypes"].ToString(); } set { ViewState["FileTypes"] = value; } } } }
3,服务端后台返回数据(这里采用服务器端程序:aspx.cs)
1,Upload.ashx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using HMFW.Model; using HMFW.Web.App_Code; using System.IO; namespace HMFW.Web.SWFUpload { /// <summary> /// Upload 的摘要说明 /// </summary> public class Upload : BaseHandler { protected override void ActionHandler(string action) { switch (action.ToLower()) { case "getfiles": GetFiles(); break; default: UploadFile(); break; } } /// <summary> /// 测试Js加载数据 /// </summary> private void GetFiles() { List<FileModel> files = new List<FileModel>(); FileModel file = new FileModel() { SystemName = "3dc2dd9d-9c7f-4f25-9c10-6760eec826a7.jpg", ShowName = "数钱.jpg", ServerID = "3dc2dd9d-9c7f-4f25-9c10-6760eec826a7", ClientID = "3dc2dd9d-9c7f-4f25-9c10-6760eec826a7", FileType = ".jpg", Path = "/upload/SWFUpload/SQJS_SWHD/day_111124/", ThumbnailPath = "/upload/SWFUpload/SQJS_SWHD/day_111124/3dc2dd9d-9c7f-4f25-9c10-6760eec826a7_thumb.jpg" }; files.Add(file); FileModel file1 = new FileModel() { SystemName = "3108eb8e-ff43-4b7f-adb6-f65b1b48fcfc.doc", ShowName = "文件.txt", ServerID = "3108eb8e-ff43-4b7f-adb6-f65b1b48fcfc", ClientID = "3108eb8e-ff43-4b7f-adb6-f65b1b48fcfc", FileType = ".txt", Path = "/upload/SWFUpload/SQJS_SWHD/day_111124/", ThumbnailPath = "/SWFUpload/images/doc.png" }; files.Add(file1); Output(JsonHelper.ModelToJsonString<List<FileModel>>(files)); } #region 上传文件方法 /// <summary> /// 上传文件方法 /// </summary> private void UploadFile() { System.Drawing.Image original_image = null; //string srvUploadPath = Server.MapPath(_context.Session["ServerUploadPath"].ToString()); //if (_context.Session["ServerUploadPath"] == null) //{ // _context.Session["ServerUploadPath"] = "/upload/SWFUpload/"; //} string SettingUploadPath = HMFW.Common.GlobalSettings.Instance.SWFUploadPath; if (!string.IsNullOrEmpty(_context.Request["UploadPathAdd"]))//如果需要在默认上传路径上再加一个文件夹 { SettingUploadPath += _context.Request["UploadPathAdd"] + "/"; } if (_context.Request["BindsAreaCode"] == "True")//如果需要在默认上传路径上再加个人地区编码对应的文件夹 { SettingUploadPath += GetSessionCurrentUserInfo.sAreaCode + "/"; } string UploadPath = SettingUploadPath + "day_" + DateTime.Now.ToString("yyMMdd") + "/"; //获取设置的上传服务器物理路径/upload/SWFUpload/day_111123/ string srvUploadPath = _context.Server.MapPath(UploadPath); CreateDir(UploadPath); try { // Get the data HttpPostedFile jpeg_image_upload = _context.Request.Files["Filedata"]; string temp = jpeg_image_upload.ContentType; //获取后缀.jpg string FileType = ImgHelper.GetExtentionFileName(jpeg_image_upload.FileName).ToLower(); //定义缩略图的相对路径 string FilePathTemp = ""; string guidFileName = Guid.NewGuid().ToString(); //如果为图片文件则 if (ImgHelper.IsImageFile(FileType)) { // Retrieve the uploaded image original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream); //保存缩略图(物理路径参数) ImgHelper.CompressAsPath(original_image, new System.Drawing.Rectangle(0, 0, 100, 100), srvUploadPath + guidFileName + "_thumb" + FileType); FilePathTemp = UploadPath + guidFileName + "_thumb" + FileType; } //为其他类型的文件的话缩略图不用生成 else { //文件类型不加点("txt"而不是".txt") string FileTypeName = FileType.Substring(1, FileType.Length - 1); FilePathTemp = "~/SWFUpload/images/" + FileTypeName + ".png"; } //保存实际图片或文件 jpeg_image_upload.SaveAs(srvUploadPath + guidFileName + FileType); _context.Response.StatusCode = 200; System.Web.UI.Page page = new System.Web.UI.Page(); page.AppRelativeVirtualPath = _context.Request.AppRelativeCurrentExecutionFilePath; page.ProcessRequest(_context); FileModel FileModel = new FileModel() { ServerID = guidFileName, FileType = FileType, Path = UploadPath, ShowName = jpeg_image_upload.FileName, SystemName = guidFileName + FileType, ThumbnailPath = page.ResolveUrl(FilePathTemp), State = 0 }; var sjos = JsonHelper.ModelToJsonString<FileModel>(FileModel); Output(JsonHelper.ModelToJsonString<FileModel>(FileModel));// thumbnail_id } catch { // If any kind of error occurs return a 500 Internal Server error _context.Response.StatusCode = 500; _context.Response.Write("An error occured"); //Response.End(); } finally { // Clean up if (original_image != null) original_image.Dispose(); _context.Response.End(); } } #endregion #region 创建文件夹 /// <summary> /// 创建文件夹 /// </summary> /// <param name="srvPath"></param> private void CreateDir(string srvPath) { if (!File.Exists(_context.Server.MapPath(srvPath))) { Directory.CreateDirectory(_context.Server.MapPath(srvPath)); } } #endregion #region 根据路径获取文件名,带后缀 /// <summary> /// 根据路径获取文件名,带后缀 /// </summary> /// <param name="path"></param> /// <returns></returns> private static string GetFileName(string path) { int intLast = path.LastIndexOf('/', path.Length - 1); if (intLast > 0) { return path.Substring(intLast + 1); } return string.Empty; } #endregion } }
2,DeleteFiles.ashx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using HMFW.Model; using HMFW.Web.App_Code; using BF.Web.PhotoUpload; using System.IO; namespace HMFW.Web.SWFUpload { /// <summary> /// 对SWFUpload上传的文件进行删除 /// </summary> public class DeleteFiles : BaseHandler { protected override void ActionHandler(string action) { switch (action.ToLower()) { default: DeleteFile(); break; } } #region 删除文件 private void DeleteFile() { string deleteFiles = _context.Request["DeleteFiles"]; List<FileModel> FileModels = JsonHelper.JsonStringToList<FileModel>(deleteFiles); //List<FileModel> FileModels = serializer.Deserialize<List<FileModel>>(deleteFiles); //string[] files = deleteFiles.Split(','); try { foreach (var item in FileModels) { //string str = upload.GetExtentionFileName(item); string localFilePath = _context.Server.MapPath(item.Path + item.SystemName); string localThumbFilePath = _context.Server.MapPath(item.ThumbnailPath); File.Delete(localFilePath); //如果是源文件图片文件,才需要删除缩略图 if (ImgHelper.IsImageFile(item.FileType)) { File.Delete(localThumbFilePath); } } Output("1");//删除成功 } catch { Output("0");//删除失败 } } #endregion } }
3,ImgHelper.cs
/****************************************** * 类作用: 对swfupload上传的文件进行图像编辑(缩略图) * 建立人: 肖合明 * 建立时间: 2011/11/23 *******************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Drawing; namespace HMFW.Web.SWFUpload { /// <summary> /// 对swfupload上传的文件进行图像编辑(缩略图) /// </summary> public class ImgHelper { #region 压缩图片到指定大小,并保存在指定路径 /// <summary> /// 压缩图片到指定大小,并保存在指定路径 /// </summary> /// <param name="original_image"></param> /// <param name="targetRec"></param> /// <param name="path">保存路径</param> /// <returns>返回bool</returns> public static bool CompressAsPath(System.Drawing.Image original_image, Rectangle targetRec, string path) { bool result = true; using (Stream stream = CompressAsStream(original_image, targetRec)) { using (FileStream fs = new FileStream(path, FileMode.Create)) { byte[] buffer = ((MemoryStream)stream).GetBuffer(); fs.Write(buffer, 0, buffer.Length); } } return result; } #endregion #region 压缩图片到指定大小(供内部使用)+边框 /// <summary> /// 压缩图片到指定大小 /// </summary> /// <param name="original_image">原始图片</param> /// <param name="targetRec">矩形大小位置</param> /// <returns></returns> public static Stream CompressAsStream(System.Drawing.Image original_image, Rectangle targetRec) //int target_width, int target_height { Stream stream = new MemoryStream(); // 计算新的高度和宽度 int width = original_image.Width; int height = original_image.Height; int new_width, new_height; //Rectangle r =new Rectangle( float target_ratio = (float)targetRec.Width / (float)targetRec.Height; float image_ratio = (float)width / (float)height; if (target_ratio > image_ratio) { new_height = targetRec.Height; new_width = (int)Math.Floor(image_ratio * (float)targetRec.Height); } else { new_height = (int)Math.Floor((float)targetRec.Width / image_ratio); new_width = targetRec.Width; } new_width = new_width > targetRec.Width ? targetRec.Width : new_width; new_height = new_height > targetRec.Height ? targetRec.Height : new_height; using (System.Drawing.Bitmap final_image = new System.Drawing.Bitmap(new_width + 8, new_height + 8)) { System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(final_image); graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, new_width + 8, new_height + 8)); graphic.DrawImage(original_image, 2, 2, new_width, new_height); AddTop(ref graphic); AddTopLeft(ref graphic); AddTopRight(ref graphic); AddRight(ref graphic); AddBottomRight(ref graphic); AddBottom(ref graphic); AddBottomLeft(ref graphic); AddLeft(ref graphic); final_image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; } return stream; } #endregion #region 压缩图片到指定大小(不加边框)CompressAsBytes1(暂时没用) /// <summary> /// 压缩图片到指定大小(不加边框)(暂时没用) /// </summary> /// <param name="original_image"></param> /// <param name="targetRec"></param> /// <returns>返回byte数组</returns> public static byte[] CompressAsBytes1(System.Drawing.Image original_image, Rectangle targetRec) { Stream stream = new MemoryStream(); // 计算新的高度和宽度 int width = original_image.Width; int height = original_image.Height; int new_width, new_height; //Rectangle r =new Rectangle( float target_ratio = (float)targetRec.Width / (float)targetRec.Height; float image_ratio = (float)width / (float)height; if (target_ratio > image_ratio) { new_height = targetRec.Height; new_width = (int)Math.Floor(image_ratio * (float)targetRec.Height); } else { new_height = (int)Math.Floor((float)targetRec.Width / image_ratio); new_width = targetRec.Width; } new_width = new_width > targetRec.Width ? targetRec.Width : new_width; new_height = new_height > targetRec.Height ? targetRec.Height : new_height; using (System.Drawing.Bitmap final_image = new System.Drawing.Bitmap(new_width, new_height)) { System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(final_image); graphic.DrawImage(original_image, 0, 0, new_width, new_height); graphic.DrawRectangle(new Pen(Color.LightGray, 1), new System.Drawing.Rectangle(0, 0, final_image.Width - 1, final_image.Height - 1)); final_image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; } return ((MemoryStream)stream).GetBuffer(); } #endregion #region 压缩图片到指定大小(加边框)CompressAsBytes /// <summary> /// 压缩图片到指定大小(加边框)CompressAsBytes /// </summary> /// <param name="original_image">原始图片</param> /// <param name="targetRec"></param> /// <returns>返回byte数组</returns> public static byte[] CompressAsBytes(System.Drawing.Image original_image, Rectangle targetRec) { Stream stream = new MemoryStream(); // 计算新的高度和宽度 int width = original_image.Width; int height = original_image.Height; int new_width, new_height; //Rectangle r =new Rectangle( float target_ratio = (float)targetRec.Width / (float)targetRec.Height; float image_ratio = (float)width / (float)height; if (target_ratio > image_ratio) { new_height = targetRec.Height; new_width = (int)Math.Floor(image_ratio * (float)targetRec.Height); } else { new_height = (int)Math.Floor((float)targetRec.Width / image_ratio); new_width = targetRec.Width; } new_width = new_width > targetRec.Width ? targetRec.Width : new_width; new_height = new_height > targetRec.Height ? targetRec.Height : new_height; using (System.Drawing.Bitmap final_image = new System.Drawing.Bitmap(new_width + 8, new_height + 8)) { System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(final_image); graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, new_width + 8, new_height + 8)); graphic.DrawImage(original_image, 2, 2, new_width, new_height); AddTop(ref graphic); AddTopLeft(ref graphic); AddTopRight(ref graphic); AddRight(ref graphic); AddBottomRight(ref graphic); AddBottom(ref graphic); AddBottomLeft(ref graphic); AddLeft(ref graphic); final_image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Position = 0; } return ((MemoryStream)stream).GetBuffer(); } #endregion #region 给图片加边框的一些操作方法 /// <summary> /// 给图片加top边框 /// </summary> /// <param name="graphic"></param> private static void AddTop(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/top.bmp"); using (System.Drawing.Image topImage = System.Drawing.Image.FromFile(path)) { graphic.DrawImage(topImage, 2, 0, graphic.VisibleClipBounds.Size.Width - 8, 2); } } /// <summary> /// 给图片加Topleft边框 /// </summary> /// <param name="graphic"></param> private static void AddTopLeft(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/topLeft.bmp"); using (System.Drawing.Image topLeftImage = new Bitmap(path)) { graphic.DrawImage(topLeftImage, 0, 0, 2, 2); } } /// <summary> /// 给图片加Topright边框 /// </summary> /// <param name="graphic"></param> private static void AddTopRight(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/topRight.bmp"); using (System.Drawing.Image topRightImage = new Bitmap(path)) { graphic.DrawImage(topRightImage, graphic.VisibleClipBounds.Size.Width - 6, 0, 6, 7); } } /// <summary> /// 给图片加Right边框 /// </summary> /// <param name="graphic"></param> private static void AddRight(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/Right.bmp"); using (System.Drawing.Image rightImage = new Bitmap(path)) { graphic.DrawImage(rightImage, graphic.VisibleClipBounds.Size.Width - 6, 7, 6, graphic.VisibleClipBounds.Size.Height - 7 - 6); } } /// <summary> /// 给图片加ButtomRight边框 /// </summary> /// <param name="graphic"></param> private static void AddBottomRight(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/bottomRight.bmp"); using (System.Drawing.Image bottomRightImage = new Bitmap(path)) { graphic.DrawImage(bottomRightImage, graphic.VisibleClipBounds.Size.Width - 6, graphic.VisibleClipBounds.Size.Height - 6, 6, 6); } } /// <summary> /// 给图片加Bottom边框 /// </summary> /// <param name="graphic"></param> private static void AddBottom(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/bottom.bmp"); using (System.Drawing.Image bottomImage = new Bitmap(path)) { graphic.DrawImage(bottomImage, 2, graphic.VisibleClipBounds.Size.Height - 6, graphic.VisibleClipBounds.Size.Width - 8, 6); } } /// <summary> /// 给图片加BottomLeft边框 /// </summary> /// <param name="graphic"></param> private static void AddBottomLeft(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/bottomLeft.bmp"); using (System.Drawing.Image bottomLeftImage = new Bitmap(path)) { graphic.DrawImage(bottomLeftImage, 0, graphic.VisibleClipBounds.Size.Height - 6, 2, 2); } } /// <summary> /// 给图片加Left边框 /// </summary> /// <param name="graphic"></param> private static void AddLeft(ref System.Drawing.Graphics graphic) { string path = HttpContext.Current.Server.MapPath("~/SWFUpload/images/Thumb/left.bmp"); using (System.Drawing.Image leftImage = new Bitmap(path)) { graphic.DrawImage(leftImage, 0, 2, 2, graphic.VisibleClipBounds.Size.Height - 8); } } #endregion #region 根据后缀名判断是否为系统设置的图片文件 /// <summary> /// 根据后缀名判断是否为系统设置的图片文件 /// </summary> /// <param name="ExtentionFileName"></param> /// <returns>true为图片文件,false不是图片文件</returns> public static bool IsImageFile(string ExtentionFileName) { bool result = false; string[] imageList = new string[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif" }; foreach (string item in imageList) { if (item == ExtentionFileName) { result = true; break; } } return result; } #endregion #region 根据文件名获取后缀 /// <summary> /// 根据文件名获取后缀 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static string GetExtentionFileName(string fileName) { int intLast = fileName.LastIndexOf('.', fileName.Length - 1); if (intLast > 0) { return fileName.Substring(intLast); } return string.Empty; } #endregion } }
标签:批量上传图片
原文地址:http://blog.csdn.net/hr1187362408/article/details/46427455