【ASP.NET】swfuplod图片上传
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【ASP.NET】swfuplod图片上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                根據網上例子簡單實現了圖片上傳和修改的時候默認顯示。
 
我是圖片預覽的時候存在了緩沖session里面,這里要改Global.asax文件不然session火狐會失效。
Global.asax文件修改:
 
根據例子修改了如下頁面文件,因為前天用到了jquery的放大鏡圖片效果所以這里生產了3種不同尺寸大小的圖片。
upload.aspx文件修改:
 
 
handler.js文件修改: function fileQueueError(file, errorCode, message) {try {if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {alert("上傳文件過多.\n" + (message === 0 ? "你已經達到上傳限制." : "您還可以選擇上傳 " + message + " 圖片."));return;}var imageName = "error.gif";var errorName = "";if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {errorName = "You have attempted to queue too many files.";}if (errorName !== "") {alert(errorName);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:alert(message);break;}addImage("images/" + imageName);} catch (ex) {this.debug(ex);}}function fileDialogComplete(numFilesSelected, numFilesQueued) {try {if (numFilesQueued > 0) {this.startUpload();}} catch (ex) {this.debug(ex);} }function uploadProgress(file, bytesLoaded) {// try { // var percent = Math.ceil((bytesLoaded / file.size) * 100);// var progress = new FileProgress(file, this.customSettings.upload_target); // progress.setProgress(percent); // if (percent === 100) { // progress.setStatus("Creating thumbnail..."); // progress.toggleCancel(false, this); // } else { // progress.setStatus("Uploading..."); // progress.toggleCancel(true, this); // } // } catch (ex) { // this.debug(ex); // } }function uploadSuccess(file, serverData) {try { // var progress = new FileProgress(file, this.customSettings.upload_target); // progress.setStatus("上傳成功!"); // progress.toggleCancel(false); // progress.setFileValue(file.id, serverData); // progress.setImg("swfupload/thumbnail.aspx?id=" + serverData);showMyImage(serverData);} catch (ex) {this.debug(ex);} }function uploadComplete(file) {this.setButtonDisabled(false);var stats = this.getStats();var status = document.getElementById("divStatus");status.innerHTML = "已上傳 " + stats.successful_uploads + " 個圖片,還可以上傳" + parseInt(this.settings['file_upload_limit'] - stats.successful_uploads) + "個圖片"; // 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.setStatus("上傳成功!"); // progress.toggleCancel(false); // } // } 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:alert(message);break;}addImage("images/" + imageName);} catch (ex3) {this.debug(ex3);}}function addImage(src) {var newImg = document.createElement("img");newImg.style.margin = "5px";document.getElementById("thumbnails").appendChild(newImg);if (newImg.filters) {try {newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;} catch (e) {// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';}} else {newImg.style.opacity = 0;}newImg.onload = function () {fadeIn(newImg, 0);};newImg.src =src; }function showImage(src,file) {var newImg = document.createElement("img");newImg.style.margin = "5px";newImg.src =src;newImg.id= file.id;document.getElementById("thumbnails").appendChild(newImg); // if (newImg.filters) { // try { // newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0; // } catch (e) { // // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. // newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')'; // } // } else { // newImg.style.opacity = 0; // }// newImg.onload = function () { // fadeIn(newImg, 0); // };}//顯示我的圖片songss 2013年12月27日 function showMyImage(pid) {if (pid == "") {return;}var id = "SWFUpload_0_" + pid;this.fileProgressID = "divFileProgress" + pid;this.fileProgressWrapper = document.getElementById(this.fileProgressID);if (!this.fileProgressWrapper) {this.fileProgressWrapper = document.createElement("li");this.fileProgressWrapper.className = "progressWrapper";this.fileProgressWrapper.id = this.fileProgressID;this.fileProgressElement = document.createElement("div");this.fileProgressElement.className = "progressContainer blue";var progressCancel = document.createElement("a");progressCancel.className = "progressCancel";progressCancel.style.visibility = "visible";progressCancel.onclick = function () { delDiv("divFileProgress" + pid); };progressCancel.appendChild(document.createTextNode(" X "));var progressText = document.createElement("div");progressText.className = "progressName";progressText.appendChild(document.createTextNode(""));var progressBar = document.createElement("div");progressBar.className = "progressBarInProgress";var progressStatus = document.createElement("div");progressStatus.className = "progressBarStatus";progressStatus.innerHTML = "?";var progressImg = document.createElement("img");progressImg.style.width = "105px";progressImg.src = "swfupload/thumbnail.aspx?id=" + pid;progressImg.id = id;this.fileProgressElement.appendChild(progressCancel);this.fileProgressElement.appendChild(progressText);this.fileProgressElement.appendChild(progressStatus);this.fileProgressElement.appendChild(progressBar);this.fileProgressElement.appendChild(progressImg);this.fileProgressWrapper.appendChild(this.fileProgressElement);document.getElementById("divFileProgressContainer").appendChild(this.fileProgressWrapper);fadeIn(this.fileProgressWrapper, 0);if (progressImg.filters) {try {progressImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;} catch (e) {// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.progressImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';}} else {progressImg.style.opacity = 0;}progressImg.onload = function () {fadeIn(progressImg, 0);};} else {this.fileProgressElement = this.fileProgressWrapper.firstChild;this.fileProgressElement.childNodes[1].firstChild.nodeValue = "";}this.height = this.fileProgressWrapper.offsetHeight;$('<input />', {type: "hidden",val: pid,id: "value_" + id,name: "fileUrl"}).appendTo(this.fileProgressElement);}function delDiv(mydiv) {document.getElementById("divFileProgressContainer").removeChild(document.getElementById(mydiv));//swfu參見頁面中的 swfu = new SWFUpload(settings);var stats = swfu.getStats();stats.successful_uploads--;swfu.setStats(stats);var status = document.getElementById("divStatus");status.innerHTML = "已上傳 " + stats.successful_uploads + " 個圖片,還可以上傳" + parseInt(swfu.settings['file_upload_limit'] - stats.successful_uploads) + "個圖片"; }function cancelUpload() {var obj=document.getElementById("SWFUpload_0_0")document.getElementById("thumbnails").removeChild(obj); } function fadeIn(element, opacity) {var reduceOpacityBy = 5;var rate = 30; // 15 fpsif (opacity < 100) {opacity += reduceOpacityBy;if (opacity > 100) {opacity = 100;}if (element.filters) {try {element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;} catch (e) {// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';}} else {element.style.opacity = opacity / 100;}}if (opacity < 100) {setTimeout(function () {fadeIn(element, opacity);}, rate);} }/* ******************************************* FileProgress Object* Control object for displaying file info* ****************************************** */function FileProgress(file, targetID) {this.fileProgressID = "divFileProgress"+file.id;this.fileProgressWrapper = document.getElementById(this.fileProgressID);if (!this.fileProgressWrapper) {this.fileProgressWrapper = document.createElement("li");this.fileProgressWrapper.className = "progressWrapper";this.fileProgressWrapper.id = this.fileProgressID;this.fileProgressElement = document.createElement("div");this.fileProgressElement.className = "progressContainer";var progressCancel = document.createElement("a");progressCancel.className = "progressCancel";progressCancel.href = "#";progressCancel.style.visibility = "visible";progressCancel.appendChild(document.createTextNode(" X "));var progressText = document.createElement("div");progressText.className = "progressName";progressText.appendChild(document.createTextNode(""));var progressBar = document.createElement("div");progressBar.className = "progressBarInProgress";var progressStatus = document.createElement("div");progressStatus.className = "progressBarStatus";progressCancel.style.visibility = "hidden";progressStatus.innerHTML = "?";var progressImg = document.createElement("img");progressImg.style.width = "105px";progressImg.id=file.id;this.fileProgressElement.appendChild(progressCancel);this.fileProgressElement.appendChild(progressText);this.fileProgressElement.appendChild(progressStatus);this.fileProgressElement.appendChild(progressBar);this.fileProgressElement.appendChild(progressImg);this.fileProgressWrapper.appendChild(this.fileProgressElement);document.getElementById(targetID).appendChild(this.fileProgressWrapper);fadeIn(this.fileProgressWrapper, 0);} else {this.fileProgressElement = this.fileProgressWrapper.firstChild;this.fileProgressElement.childNodes[1].firstChild.nodeValue = "";}this.height = this.fileProgressWrapper.offsetHeight;} FileProgress.prototype.setProgress = function (percentage) {this.fileProgressElement.className = "progressContainer green";this.fileProgressElement.childNodes[3].className = "progressBarInProgress";//this.fileProgressElement.childNodes[3].style.width = percentage + "%"; }; FileProgress.prototype.setComplete = function () {this.fileProgressElement.className = "progressContainer blue";this.fileProgressElement.childNodes[3].className = "progressBarComplete";this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setError = function () {this.fileProgressElement.className = "progressContainer red";this.fileProgressElement.childNodes[3].className = "progressBarError";this.fileProgressElement.childNodes[3].style.width = "";}; FileProgress.prototype.setCancelled = function () {this.fileProgressElement.className = "progressContainer";this.fileProgressElement.childNodes[3].className = "progressBarError";this.fileProgressElement.childNodes[3].style.width = "";}; FileProgress.prototype.setStatus = function (status) {this.fileProgressElement.childNodes[2].innerHTML = status; }; FileProgress.prototype.setImg = function (src) {this.fileProgressElement.childNodes[4].src = src; };FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {//this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";this.fileProgressElement.childNodes[0].style.visibility ="visible" ;if (swfuploadInstance) {var fileID = this.fileProgressID;this.fileProgressElement.childNodes[0].onclick = function () {swfuploadInstance.cancelUpload(fileID);var thumdNode=document.getElementById(fileID);thumdNode.parentNode.removeChild(thumdNode);return false;};} };FileProgress.prototype.setFileValue = function (id, url) {$('<input />', {type: "hidden",val: url,id: "value_" + id,name: "fileUrl"}).appendTo(this.fileProgressElement);}; 這個就加了個字段
Thumbnail.cs文件修改:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;/// <summary> /// Summary description for Thumbnail /// </summary> namespace WMP.Web.user {public class Thumbnail{private string id;private byte[] originalData;private byte[] data;private byte[] centerdata;public Thumbnail(string id, byte[] originalData, byte[] data, byte[] centerdata){this.ID = id;this.OriginalData = originalData;this.Data = data;this.Centerdata = centerdata;}public string ID{get{return this.id;}set{this.id = value;}}public byte[] OriginalData{get{return this.originalData;}set{this.originalData = value;}}public byte[] Data{get{return this.data;}set{this.data = value;}}public byte[] Centerdata{get{return this.centerdata;}set{this.centerdata = value;}}}}
提交的時候記得sesion什么時候該清空。
部分提交代碼:
? ?
protected void Page_Load(object sender, EventArgs e){if (!Page.IsPostBack){Session.Remove("file_info");}}string[] picArr = Request.Form["fileUrl"].Split(',');foreach (Thumbnail img in thumbnails){for (int i = 0; i < picArr.Length;i++ ){if (picArr[i] == img.ID){name1 = img.ID + ".jpg";name2 = "s_" + img.ID + ".jpg";name3 = "c_" + img.ID + ".jpg";FileStream fs1 = new FileStream(UploadPath1 + img.ID + ".jpg", FileMode.Create);BinaryWriter bw1 = new BinaryWriter(fs1);bw1.Write(img.OriginalData);bw1.Close();fs1.Close();FileStream fs2 = new FileStream(UploadPath2 + "s_" + img.ID + ".jpg", FileMode.Create);BinaryWriter bw2 = new BinaryWriter(fs2);bw2.Write(img.Data);bw2.Close();fs2.Close();FileStream fs3 = new FileStream(UploadPath3 + "c_" + img.ID + ".jpg", FileMode.Create);BinaryWriter bw3 = new BinaryWriter(fs3);bw3.Write(img.Centerdata);bw3.Close();fs3.Close();if (i != 0){fileIds += ",";}imgModel.id = Guid.NewGuid().ToString().Replace("-", "");fileName = img.ID;imgModel.fileName = fileName;imgModel.filePath = "productImages/";imgModel.fileType = ".jpg";imgBll.Add(imgModel);fileIds += imgModel.id;}}}Session.Remove("file_info");
修改的頁面初始化: var imgIds = "";function setImgId(str) {imgIds = str;}var swfu;window.onload = function () {swfu = new SWFUpload({// Backend Settingsupload_url: "swfupload/upload.aspx",post_params: {"ASPSESSID": "<%=Session.SessionID %>"},// File Upload Settingsfile_size_limit: 1024,file_types: "*.jpg;*.gif;*.png",file_types_description: "JPG Images",file_upload_limit: 4, //限制上傳文件數目file_queue_limit: 5, //限制每次選擇文件的數目,0為不限制file_queue_error_handler: fileQueueError,file_dialog_complete_handler: fileDialogComplete,upload_progress_handler: uploadProgress,upload_error_handler: uploadError,upload_success_handler: uploadSuccess,upload_complete_handler: uploadComplete,swfupload_loaded_handler: loaded,// Button settingsbutton_image_url: "swfupload/images/uploadbutt.jpg",button_placeholder_id: "spanButtonPlaceholder",button_width: 89,button_height: 28,button_text: '<span class="button"> </span>',button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 16pt; } .buttonSmall { font-size: 10pt; }',button_text_top_padding: 2,button_text_left_padding: 5,// Flash Settingsflash_url: "swfupload/swfupload/swfupload.swf", // Relative to this filecustom_settings: {upload_target: "divFileProgressContainer"},// Debug Settingsdebug: false});//再在handlers.js定義loaded函數[javascript]view plaincopyfunction loaded() {var imgArr = imgIds.split(",");for (var i = 0; i < imgArr.length; i++) {addImageFromDb(imgArr[i], this);}}//調用addImageFromDb函數 修改已上傳的圖片數量 并且生成已上傳的圖片的縮略圖////src_s為生成的縮略圖地址//src_b為原圖地址//serverData是圖片上傳處理頁面返回的數據 成功則以 success|縮略圖地址|原圖地址 這樣的格式返回//初始化已經上傳過的圖片function addImageFromDb(id, swfu) {if (id == "") {return;}var stats = swfu.getStats();stats.successful_uploads++;swfu.setStats(stats);showMyImage(id);var status = document.getElementById("divStatus");status.innerHTML = "已上傳<font color='green'>" + stats.successful_uploads + "</font>張,還可以上傳<font color='red'>" + parseInt(swfu.settings['file_upload_limit'] - stats.successful_uploads) + "</font>張";}}
新增頁面沒什么就例子里面的 var swfu;window.onload = function () {swfu = new SWFUpload({// Backend Settingsupload_url: "swfupload/upload.aspx",post_params: {"ASPSESSID": "<%=Session.SessionID %>"},// File Upload Settingsfile_size_limit: 1024,file_types: "*.jpg;*.gif;*.png",file_types_description: "JPG Images",file_upload_limit: 4, //限制上傳文件數目file_queue_limit: 5, //限制每次選擇文件的數目,0為不限制// 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_dialog_complete_handler: fileDialogComplete,upload_progress_handler: uploadProgress,upload_error_handler: uploadError,upload_success_handler: uploadSuccess,upload_complete_handler: uploadComplete,// Button settingsbutton_image_url: "swfupload/images/uploadbutt.jpg",button_placeholder_id: "spanButtonPlaceholder",button_width: 89,button_height: 28,button_text: '<span class="button"> </span>',button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 16pt; } .buttonSmall { font-size: 10pt; }',button_text_top_padding: 2,button_text_left_padding: 5,// Flash Settingsflash_url: "swfupload/swfupload/swfupload.swf", // Relative to this filecustom_settings: {upload_target: "divFileProgressContainer"},// Debug Settingsdebug: false});}
半夜寫的,比較匆忙,給自己一個筆記。
原帖地址:http://blog.csdn.net/hateson/article/details/17976945?
 
 
http://download.csdn.net/detail/hateson/6822219?源碼地址
 
總結
以上是生活随笔為你收集整理的【ASP.NET】swfuplod图片上传的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Windows的Git Bash使用tr
- 下一篇: 银行家算法
