SWFupload上传插件案例及头像的截取

时间:2022-08-29 16:55:56

记录一下这个上传插件的使用方法吧,以后项目中肯定会用到,到时候可以拿来用。一些属性什么的就不贴了。

流程:

1、引入相应的js文件 。这里还用了imgareaselect插件。代码中注释部分是未使用imgareaselect插件的方式,之前用的是jqueryui。。之后改为了imgareaselect插件的方式

2、实例化SWFUpload对象,传入一个配置参数对象进行各方面的配置。 
3、点击SWFUpload提供的Flash按钮,弹出文件选取窗口选择要上传的文件; 
4、文件选取完成后符合规定的文件会被添加到上传的队列里; 
5、调用startUpload方法让队列里文件开始上传; 

6、文件上传过程中会触发相应的事件,开发者利用这些事件来更新ui、处理错误、发出提示等等; 

javascript代码

<script src="../js/jquery-1.7.1.js"></script>
<script src="../js/jquery.imgareaselect.min.js"></script><%--用于头像截取--%>
<script src="../SWFUpload/swfupload.js"></script>
<script src="../SWFUpload/handlers.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "/ashx/upload.ashx?action=upload",
post_params: {
"ASPSESSID": "<%=Session.SessionID %>"
},
// File Upload Settings
file_size_limit: "2 MB",
file_types: "*.jpg;*.gif",
file_types_description: "JPG Images",
file_upload_limit: 0, // 上传文件的总个数,0表示无限制
file_queue_limit: 0,//每次能上传的文件个数,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.
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: showImage,
upload_complete_handler: uploadComplete,


// Button settings
button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png",
button_placeholder_id: "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text: '<span class="button">请选择上传图片<span class="buttonSmall">(2 MB Max)</span></span>',
button_text_style: '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 1,
button_text_left_padding: 5,


// Flash Settings
flash_url: "/SWFUpload/swfupload.swf",// Relative to this file
flash9_url: "/SWFUpload/swfupload_FP9.swf",// Relative to this file


custom_settings: {
upload_target: "divFileProgressContainer"
},


// Debug Settings
debug: false
});
}
//上传成功以后调用该方法
function showImage(file, serverData) {
// $("#showPhoto").attr("src", serverData);
var data = serverData.split(':');
//将上传成功的图片作为DIV的背景
// $("#hiddenImageUrl").val(data[0]);//将上传成功的图片路径存储到隐藏域中。
/// $("#divContent").css("backgroundImage", "url('" + data[0] + "')").css("width",data[1]+"px").css("height",data[2]+"px");
$("#selectbanner").attr("src", data[0]);
$('#selectbanner').imgAreaSelect({
selectionColor: 'blue', x1: 0, y1: 0, x2: 100,
y2: 100,selectionOpacity: 0.2, onSelectEnd: preview
});


}
//选择结束以后调用该方法
function preview(img, selection) {
$('#selectbanner').data('x', selection.x1);
$('#selectbanner').data('y', selection.y1);
$('#selectbanner').data('w', selection.width);
$('#selectbanner').data('h', selection.height);
}

$(function () {
//让DIV可以移动与拖动大小
//$("#divCut").draggable({ containment: "#divContent", scroll: false }).resizable({
// containment: "#divContent"
//});
$("#btnCut").click(function () {
cutPhoto();
});
})
//截取头像
function cutPhoto() {
//计算要截取的头像的范围。
//var y = $("#divCut").offset().top - $("#divContent").offset().top;//纵坐标 offset():获取某个元素的绝对坐标。
//var x = $("#divCut").offset().left - $("#divContent").offset().left;
//var width = $("#divCut").width();
//var heigth = $("#divCut").height();
var pars = {
"x": $('#selectbanner').data('x'),


"y": $('#selectbanner').data('y'),


"width": $('#selectbanner').data('w'),


"height": $('#selectbanner').data('h'),
"action": "cut",
"imgSrc": $("#selectbanner").attr("src")

};
$.post("/ashx/upload.ashx", pars, function (data) {
$("#showPhoto").attr("src",data);
});
}
</script>


HTML代码

 

<form id="form1" runat="server">
<div id="content">
<div id="swfu_container" style="margin: 0px 10px;">
<div>
<span id="spanButtonPlaceholder"></span>
</div>
<div id="divFileProgressContainer" style="height: 75px;"></div>
<div id="thumbnails"></div>
<%--<div id="divContent" style="width:300px; height:300px;">
<div id="divCut" style="width:100px;height:100px; border:solid red 1px">
</div>
</div>--%>
<input type="button" value="截取图片" id="btnCut" />
<input type="hidden" id="hiddenImageUrl" />

<%--<div id="selectbanner">
</div>--%>
<img id="selectbanner"/>
<img id="showPhoto"/>
</div>
</div>
</form>

服务端代码

 public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string action = context.Request["action"];
if (action == "upload")//上传图片
{
ProcessFileUpload(context);
}
else if (action =="cut")//截取图片
{
ProcessCutPhoto(context);
}
else
{
context.Response.Write("参数错误!!");
}
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="context"></param>
private void ProcessFileUpload(HttpContext context)
{
HttpPostedFile file = context.Request.Files["Filedata"];
if (file != null)
{
string fileName = Path.GetFileName(file.FileName);
string fileExt = Path.GetExtension(fileName);
if (fileExt == ".jpg")
{
string dir = "/ImageUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
if (!Directory.Exists(context.Request.MapPath(dir)))
{
Directory.CreateDirectory(context.Request.MapPath(dir));
}
string newfileName = Guid.NewGuid().ToString();
string fullDir = dir + newfileName + fileExt;
file.SaveAs(context.Request.MapPath(fullDir));
using (Image img = Image.FromFile(context.Request.MapPath(fullDir)))
{
context.Response.Write(fullDir + ":" + img.Width + ":" + img.Height);
}


//file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName));
//context.Response.Write("/ImageUpload/" + fileName);
}
}
}


/// <summary>
/// 图片的截取
/// </summary>
/// <param name="context"></param>
private void ProcessCutPhoto(HttpContext context)
{
int x = Convert.ToInt32(context.Request["x"]);
int y = Convert.ToInt32(context.Request["y"]);
int width = Convert.ToInt32(context.Request["width"]);
int height = Convert.ToInt32(context.Request["height"]);
string imgSrc = context.Request["imgSrc"];//获取上传成功的图片的路径
using (Bitmap map = new Bitmap(width, height))
{
using (Graphics g = Graphics.FromImage(map))
{
using (Image img = Image.FromFile(context.Request.MapPath(imgSrc)))
{
//第一个参数:表示画哪张图片.
//二:画多么大。
//三:画原图的哪块区域
g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
string newfileName = Guid.NewGuid().ToString();
string fullDir = "/ImageUpload/" + newfileName + ".jpg";
map.Save(context.Request.MapPath(fullDir),System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.Write(fullDir);

}

}
}
}