使用SWFUpload組件實現無刷新上傳,配合JQuery UI實現頭像截取
SWFUpload配置與使用
//1.1 引入腳本文件
<script src="SWFUpload/swfupload.js" type="text/javascript"></script> //script1
<script src="SWFUpload/handlers.js" type="text/javascript"></script> //script2
//1.2 SWFUpload配置使用
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "UpLoadPhoto.ashx?action=uploadPhoto", //
post_params: {
"ASPSESSID": "<%=Session.SessionID %>"
},
//上傳設置
file_size_limit: "10 MB", //限制上傳文件大小
file_types: "*.jpg", //限制文件格式
file_types_description: "JPG Images",
file_upload_limit: 0, //Zero means unlimited
file_post_name: "ajaxFile",
//事件設置
swfupload_preload_handler: preLoad,
swfupload_load_failed_handler: loadFailed,
file_queue_error_handler: fileQueueError,
file_dialog_complete_handler: fileDialogComplete,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError,
upload_success_handler: Success, //上傳后執行 將image的相對路徑返回
upload_complete_handler: uploadComplete,
//上傳按鈕設置
button_image_url: "SWFUpload/images/XPButtonNoText_160x22.png",
button_placeholder_id: "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text: '
',
button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 1,
button_text_left_padding: 5,
// Flash Settings
flash_url: "../swfupload/swfupload.swf", // 相對路徑
flash9_url: "../swfupload/swfupload_FP9.swf", // 相對路徑
custom_settings: {
//upload_target: "divFileProgressContainer"
},
//Debug Settings
debug: false
});
};
var data; //保存上傳的照片的路徑和文件名
function Success(file, serverData) {
var filePath = serverData.split("|")[1];
if (filePath!="undefined"||filePath!="") {
data = filePath;
$("#leftContainer").css("backgroundImage", "url(" + filePath + ")");
} else {
alert("上傳錯誤!");
}
};<!-- 2.Aspx上傳按鈕、截取按鈕等 --> <div id="Container"> <div id="topContainer"> <div id="swfu_container" style="width: 50px; height: 30px;"> <div> <span id="spanButtonPlaceholder"></span> </div> <%-- <div id="divFileProgressContainer" style="height: 75px;"> 返回信息 </div>--%> </div> </div> <div id="leftContainer" style="clear: both;"> <div id="cutDiv" style="border: 1px solid red; width: 100px; height: 100px;"> </div> </div> <div id="rigthContainer"> <div style="width: 100px; height: 100px;"> <img id="imgok" src="" alt="imgPhoto" /> </div> </div> <div id="bottomContainer" style="clear: both;"> <input type="button" id="btnCut" value="截取" style="margin: 10px auto 0px auto;" /> </div> </div>
截取
//用JQuery UI resizable(大小)、draggable(拖動) 獲取image的坐標 $(function () { $("#cutDiv").resizable({ aspectRatio: 1 / 1, maxHeight: 180, maxWidth: 180, minHeight: 48, minWidth: 48 }).draggable({ containment: 'parent' }); //獲取要截取頭像的坐標 $("#btnCut").click(function () { //獲取絕對坐標 var relTop = $("#cutDiv").offset().top - $("#leftContainer").offset().top; var relLeft = $("#cutDiv").offset().left - $("#leftContainer").offset().left; var width = $("#cutDiv").width(); var height = $("#cutDiv").height(); $.post("AjaxPhoto.ashx", { "action": "cutPhoto", "top": relTop, "left": relLeft, "width": width, "height": height, "imgSrc": data }, function (msg) { $("#imgok").attr("src", msg); //設置img路徑。 }, "text"); }); });
后台處理
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string action = context.Request["action"]; if (action == "uploadPhoto") { UpLoadPhoto(context); } else { CutPhoto(context); } } /// <summary> /// 上傳照片並生成縮略圖 /// </summary> private void UpLoadPhoto(HttpContext context) { HttpPostedFile postedFile = context.Request.Files["ajaxFile"]; if (postedFile == null) { context.Response.Write("File is null"); context.Response.End(); } string fileExtension = Path.GetExtension(postedFile.FileName); string[] containsExtentsion = { ".jpg", ".JPG", "PNG", "png" }; if (containsExtentsion.Contains(fileExtension)) { string guid = Guid.NewGuid().ToString().Substring(0, 8); string saveFileName = "Files/" + guid + fileExtension; string saveFilePath = context.Server.MapPath(saveFileName); postedFile.SaveAs(saveFilePath); using (Image image = Image.FromStream(postedFile.InputStream)) { int iWidth = 400; //生成縮略圖的寬度 int iHeightt = 400; //生成縮略圖的高度 int x = 0; int y = 0; int iOldWidth; //上傳圖片的寬度 int iOldHeight; //上傳圖片的高度 if (image.Width / (double)image.Height > iWidth / (double)iHeightt) { iOldHeight = image.Height; iOldWidth = image.Height * iWidth / iHeightt; y = 0; x = (image.Width - iOldWidth) / 2; } else { iOldWidth = image.Width; iOldHeight = image.Width * 400 / iWidth; x = 0; y = (image.Height - iOldHeight) / 2; } using (Image bitmap = new Bitmap(iWidth, iHeightt)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.InterpolationMode = InterpolationMode.High; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.Clear(Color.Transparent); graphics.DrawImage(image, new Rectangle(0, 0, iWidth, iHeightt), new Rectangle(x, y, iOldWidth, iOldHeight), GraphicsUnit.Pixel); bitmap.Save(saveFilePath); context.Response.Write("ok|" + saveFileName); } } } } else { context.Response.Write("error"); } context.Response.End(); } ///<summary> ///根據坐標生成頭像 ///</summary> private void CutPhoto(HttpContext context) { int iTop = context.Request["top"] == null ? 0 : int.Parse(context.Request["top"]); int iLeft = context.Request["left"] == null ? 0 : int.Parse(context.Request["left"]); int iWidth = context.Request["width"] == null ? 100 : int.Parse(context.Request["width"]); int iHeight = context.Request["height"] == null ? 100 : int.Parse(context.Request["height"]); string sImgSrc = context.Request["imgSrc"]; if (sImgSrc == null) { context.Response.Write("File Path is null"); context.Response.End(); } using (Image image = Image.FromFile(context.Server.MapPath(sImgSrc))) { string guid = Guid.NewGuid().ToString().Substring(0, 8); string saveFile = "Files/" + guid + ".jpg"; string saveFilePath = context.Server.MapPath(saveFile); using (Bitmap bitmap = new Bitmap(iWidth, iHeight)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.InterpolationMode = InterpolationMode.High; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.DrawImage(image, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(iLeft, iTop, iWidth, iHeight), GraphicsUnit.Pixel); bitmap.Save(saveFilePath); context.Response.Write(saveFile); context.Response.End(); } } } }
在上傳照片或圖片的時候,如果照片太大,會報錯的,解決方法在webconfig文件中找到<system.web>節點,在該節點下加入<httpRuntime maxRequestLength="900000" executionTimeout="200"/> <!--設置最大的請求報文的長度與設置請求的允許執行時間-->