【ASP.NET】swfuplod图片上传

根据网上例子简单实现了图片上传和修改的时候默认显示。


我是图片预览的时候存在了缓冲session里面,这里要改Global.asax文件不然session火狐会失效。

Global.asax文件修改:

      #region 防止火狐session丢失
        private void mySession() {
            try
            {
                string session_param_name = "ASPSESSID";
                string session_cookie_name = "ASP.NET_SESSIONID";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
                }
            }
            catch (Exception)
            {
                Response.StatusCode = 500;
                Response.Write("Error Initializing Session");
            }

            try
            {
                string auth_param_name = "AUTHID";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
                }

            }
            catch (Exception)
            {
                Response.StatusCode = 500;
                Response.Write("Error Initializing Forms Authentication");
            }
        }
        private void UpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (cookie == null)
            {
                cookie = new HttpCookie(cookie_name);
                HttpContext.Current.Request.Cookies.Add(cookie);
            }
            cookie.Value = cookie_value;
            HttpContext.Current.Request.Cookies.Set(cookie);
        }
        #endregion

根据例子修改了如下页面文件,因为前天用到了jquery的放大镜图片效果所以这里生产了3种不同尺寸大小的图片。

upload.aspx文件修改:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.IO;
using System.Collections.Generic;

namespace WMP.Web.user.swfupload
{
    public partial class upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            System.Drawing.Image thumbnail_image = null;
            System.Drawing.Image original_image = null;
            System.Drawing.Image c_original_image = null;
            System.Drawing.Image b_original_image = null;
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            System.Drawing.Bitmap c_final_image = null;
            System.Drawing.Bitmap b_final_image = null;
            System.Drawing.Graphics c_graphic = null;
            System.Drawing.Graphics b_graphic = null;
            MemoryStream ms = null;
            MemoryStream maxms = null;
            MemoryStream c_ms = null;
            MemoryStream b_ms = null;
            try
            {
                //获得数据
                HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];

                //获得上传的图片
                original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
                int width = original_image.Width;//原始图片宽度
                int height = original_image.Height;//原始图片高度

                //--目标图片存放小图
                int target_width = 68;//目标图片宽度
                int target_height = 68;//目标图片高度
                int new_width, new_height;//新宽度和新高度
                float target_ratio = (float)target_width / (float)target_height;//目标图片宽高比
                float image_ratio = (float)width / (float)height;//原始图片宽高比
                //计算新的长度和宽度
                if (target_ratio > image_ratio)
                {
                    new_height = target_height;
                    new_width = (int)Math.Floor(image_ratio * (float)target_height);
                }
                else
                {
                    new_height = (int)Math.Floor((float)target_width / image_ratio);
                    new_width = target_width;
                }
                new_width = new_width > target_width ? target_width : new_width;
                new_height = new_height > target_height ? target_height : new_height;
                //创建缩略图
                final_image = new System.Drawing.Bitmap(target_width, target_height);//目标图片的像素图
                graphic = System.Drawing.Graphics.FromImage(final_image);//目标图片的画板
                graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height));//用黑色填充目标图片大小的矩形框
                int paste_x = (target_width - new_width) / 2;//从原点位移x坐标
                int paste_y = (target_height - new_height) / 2;//从原点位移y坐标
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //插补模式
                graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);//画图
                ms = new MemoryStream();//创建一个新的内存流
                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//目标图片保存

                //--目标图片存放中图
                //生产中等图片
                int c_width = 300;//目标图片宽度--中等图片
                int c_height = 300;//目标图片高度--中等图片
                int c_new_width, c_new_height;//新宽度和新高度--中等图片
                float c_target_ratio = (float)c_width / (float)c_height;//目标图片宽高比
                float c_image_ratio = (float)width / (float)height;//原始图片宽高比
                //计算新的长度和宽度
                if (c_target_ratio > c_image_ratio)
                {
                    c_new_height = c_height;
                    c_new_width = (int)Math.Floor(c_image_ratio * (float)c_height);
                }
                else
                {
                    c_new_height = (int)Math.Floor((float)c_width / c_image_ratio);
                    c_new_width = c_width;
                }
                c_new_width = c_new_width > c_width ? c_width : c_new_width;
                c_new_height = c_new_height > c_height ? c_height : c_new_height;
                //创建缩略图
                c_final_image = new System.Drawing.Bitmap(c_width, c_height);//目标图片的像素图
                c_graphic = System.Drawing.Graphics.FromImage(c_final_image);//目标图片的画板
                c_graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, c_width, c_height));//用黑色填充目标图片大小的矩形框
                int c_paste_x = (c_width - c_new_width) / 2;//从原点位移x坐标
                int c_paste_y = (c_height - c_new_height) / 2;//从原点位移y坐标
                c_graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //插补模式
                c_graphic.DrawImage(original_image, c_paste_x, c_paste_y, c_new_width, c_new_height);//画图
                c_ms = new MemoryStream();//创建一个新的内存流
                c_final_image.Save(c_ms, System.Drawing.Imaging.ImageFormat.Jpeg);//目标图片保存
                c_ms = new MemoryStream();//创建一个新的内存流
                c_final_image.Save(c_ms, System.Drawing.Imaging.ImageFormat.Jpeg);//目标图片保存

                //--目标图片存放大图
                //生产中等图片
                int b_width = 800;//目标图片宽度--大图片
                int b_height = 800;//目标图片高度--大图片
                int b_new_width, b_new_height;//新宽度和新高度--中等图片
                float b_target_ratio = (float)b_width / (float)b_height;//目标图片宽高比
                float b_image_ratio = (float)width / (float)height;//原始图片宽高比
                //计算新的长度和宽度
                if (b_target_ratio > b_image_ratio)
                {
                    b_new_height = b_height;
                    b_new_width = (int)Math.Floor(b_image_ratio * (float)b_height);
                }
                else
                {
                    b_new_height = (int)Math.Floor((float)b_width / b_image_ratio);
                    b_new_width = b_width;
                }
                b_new_width = b_new_width > b_width ? b_width : b_new_width;
                b_new_height = b_new_height > b_height ? b_height : b_new_height;
                //创建缩略图
                b_final_image = new System.Drawing.Bitmap(b_width, b_height);//目标图片的像素图
                b_graphic = System.Drawing.Graphics.FromImage(b_final_image);//目标图片的画板
                b_graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, b_width, b_height));//用黑色填充目标图片大小的矩形框
                int b_paste_x = (b_width - b_new_width) / 2;//从原点位移x坐标
                int b_paste_y = (b_height - b_new_height) / 2;//从原点位移y坐标
                b_graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //插补模式
                b_graphic.DrawImage(original_image, b_paste_x, b_paste_y, b_new_width, b_new_height);//画图
                b_ms = new MemoryStream();//创建一个新的内存流
                b_final_image.Save(b_ms, System.Drawing.Imaging.ImageFormat.Jpeg);//目标图片保存
               
                //maxms = new MemoryStream();//创建一个新的内存流
                //original_image.Save(maxms, System.Drawing.Imaging.ImageFormat.Jpeg);//原始图片保存
                string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                Thumbnail thumb = new Thumbnail(thumbnail_id, b_ms.ToArray(), ms.ToArray(), c_ms.ToArray());

                List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>;
                if (thumbnails == null)
                {
                    thumbnails = new List<Thumbnail>();
                    Session["file_info"] = thumbnails;
                }
                thumbnails.Add(thumb);
                Response.StatusCode = 200;
                Response.Write(thumbnail_id);
            }
            catch
            {
                // If any kind of error occurs return a 500 Internal Server error
                Response.StatusCode = 500;
                Response.Write("An error occured");
                Response.End();
            }
            finally
            {
                // Clean up
                if (final_image != null) final_image.Dispose();
                if (c_final_image != null) c_final_image.Dispose();
                if (b_final_image != null) b_final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (c_graphic != null) c_graphic.Dispose();
                if (b_graphic != null) b_graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (thumbnail_image != null) thumbnail_image.Dispose();
                if (ms != null) ms.Close();
                if (maxms != null) maxms.Close();
                if (b_ms != null) b_ms.Close();
                if (c_ms != null) c_ms.Close();
                Response.End();
            }

        }
    }
}


js这里可以根据自己样式自己修改。可以弄好看点。
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 fps


	if (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 Settings
                upload_url: "swfupload/upload.aspx",
                post_params: {
                    "ASPSESSID": "<%=Session.SessionID %>"
                },

                // File Upload Settings
                file_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 settings
                button_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 Settings
                flash_url: "swfupload/swfupload/swfupload.swf", // Relative to this file

                custom_settings: {
                    upload_target: "divFileProgressContainer"
                },

                // Debug Settings
                debug: false
            });

            //再在handlers.js定义loaded函数[javascript]view plaincopy
            function 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 Settings
                upload_url: "swfupload/upload.aspx",
                post_params: {
                    "ASPSESSID": "<%=Session.SessionID %>"
                },

                // File Upload Settings
                file_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 settings
                button_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 Settings
                flash_url: "swfupload/swfupload/swfupload.swf", // Relative to this file

                custom_settings: {
                    upload_target: "divFileProgressContainer"
                },

                // Debug Settings
                debug: false
            });
        }

半夜写的,比较匆忙,给自己一个笔记。

原帖地址:http://blog.csdn.net/hateson/article/details/17976945 


http://download.csdn.net/detail/hateson/6822219 源码地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值