您的位置:首页 > 其它

swfupload实现用户文件上传以及头像的截取

2013-10-23 23:05 555 查看
网站编辑文章的时候需要插入图片、文件。如果使用FileUpload控件必须提交表单导致页面刷新,而由于AJAX不允许上传文件,所以必须使用其他解决方案。Flash提供了异步上传文件的功能,这里简介一下别人写好的flash控件:SWFUpload。

自己整理的swfupload开发包http://pan.baidu.com/s/1f3IRE

下面开始我们的图片上传旅程

swfupload上传图片文件:

前台代码:

<%--jquery-ui使用到的样式--%>
<link href="/Css/base/jquery-ui.css" rel="stylesheet" />
<%--项目中使用到了jquery,所以需引入jquery--%>
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<%--后面头像截取使用到了jquery-ui,所以这里一并引入到项目中--%>
<script src="/Scripts/jquery-ui-1.8.24.min.js"></script>
<%--下面是使用swfupload需要的一些文件,需要一并引入到项目中--%>
<link href="/lib/swfupload/css/default.css" rel="stylesheet" />
<script src="/lib/swfupload/swfupload.js"></script>
<script src="/lib/swfupload/handlers.js"></script>
<script type="text/javascript">
var filename;
var swfu;

window.onload = function () {

swfu = new SWFUpload({
// Backend Settings 设置处理上传图片的url地址。
upload_url: "fileUpLoadTest.ashx?action=up",
post_params: {
"ASPSESSID": "<%=Session.SessionID %>"
},

// File Upload Settings
file_size_limit: "2 MB",//上传文件的最大图片大小
file_types: "*.jpg",//上传图片类型
file_types_description: "JPG Images",
file_upload_limit: 0,    // 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.
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: function uploadSuccess(file, serverData) {
var files= serverData.split(':');
alert(files[1]);
//document.getElementById("divContainer").style.width = files[2] + "px";//js实现
//document.getElementById("divContainer").style.height = files[3] + "px";
//document.getElementById("divContainer").style.backgroundImage = "url(" + files[1] + ")";
//设置div的宽度和高度和背景图片的宽度和高度一致。
$("#divContainer").css("width", files[2] + "px");
$("#divContainer").css("height", files[3] + "px");
//设置div的backgroundImage的url。不能直接设置地址,必须加上"url()"
$("#divContainer").css("backgroundImage", "url(" + files[1] + ")");
//获取用户上传文件的文件名,用于截取头像时读取源图片。
filename=files[4];
},
upload_complete_handler: uploadComplete,

// Button settings
button_image_url: "/lib/swfupload/images/XPButtonNoText_160x22.png",
button_placeholder_id: "spanButtonPlaceholder",
button_width: 160,
button_height: 22,
button_text: '<span class="button">Select Images <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: "/lib/swfupload/swfupload.swf",    // Relative to this file这里需要注意文件路径。
flash9_url: "/lib/swfupload/swfupload_FP9.swf",    // Relative to this file

custom_settings: {
upload_target: "divFileProgressContainer"
},

// Debug Settings
debug: false
});
}
//-------------------------------下面是图片截取的前端代码------------------------------------------
$(function () {

$(function () {
//使用jq-ui 实现截取头像的div的移动和改变大小
$("#divCut").draggable({ containment: "parent" }).resizable({
containment: "#divContainer", aspectRatio: 1 / 1
});

$("#btnCut").click(function () {
//通过offset()方法返回的相对于浏览器的top和left值来获取截取头像div相对于图片的位置。
var divtop = $("#divCut").offset().top - $("#divContainer").offset().top;
var divleft = $("#divCut").offset().left - $("#divContainer").offset().left;
var divwidth = $("#divCut").width();
var divHeight = $("#divCut").height();
//点击按钮发送ajax请求。
$.post("fileUpLoadTest.ashx", { "action": "cut", "top": divtop, "left": divleft, "width": divwidth, "height": divHeight, "filename": filename }, function (data) {
//返回截取图片的路径并设置给img标签
$("#imgcut").attr("src", data);
})
});
})
})

</script>


页面控件布局(这里只是简单的实现,具体页面的设计并未设置):

<body>
<form id="form1" runat="server">
<div>
<span  id="spanButtonPlaceholder"></span>
</div>
<div  id="divFileProgressContainer" style="height: 75px;"></div>
<div id="divContainer"><div id="divCut" style="border:2px solid red;width:200px;height:200px"></div></div>
<input type="button" id="btnCut" value="截取" />
</form>
<img id="imgcut" alt="Alternate Text" />
</body>


后台代码:

context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
//获取客户端的action,通过判断action来判断用户是上传图片还是头像截取
string action = context.Request["action"];
//图片上传--通过action来判断的
if (context.Request["action"]=="up")
{
HttpPostedFile file = context.Request.Files["Filedata"];//通过Filedata来获取用户上传上来的文件
string name=file.FileName;//获取上传文件的全文件名
file.SaveAs(context.Server.MapPath("/img/" + name));//文件保存到项目根目录下的/img/文件夹下,以用户上传的图片名作文件的文件名。这里需要注意重复文件名的问题。具体可以通过把用户上传的文件进行md5处理后作为文件名,这样重复的文件多次上传不会保存多份,相同文件名但文件不同的通过md5处理后文件名也就不一样了。

Image img = Image.FromStream(file.InputStream);
//像客户端输出数据,返回ok表示成功,然后返回上传文件的路径在客户端可以设置div的背景图片的url为文件路径,并同时返回图片的大小来设置前端div的大小,最后还返回保存上传文件的文件名。并在头像截取的时候传递到后台。
context.Response.Write("ok:" + "/img/" + name + ":" + (img.Width) + ":" + (img.Height) + ":" + name); }
//图片截取
else if (context.Request["action"]=="cut")
{
string topstr = context.Request["top"];
string filename = context.Request["filename"];
int top = Convert.ToInt32(context.Request["top"]);
int left = Convert.ToInt32(context.Request["left"]);
int width = Convert.ToInt32(context.Request["width"]);
int height = Convert.ToInt32(context.Request["height"]);
using (Image oldImg = Image.FromFile(context.Server.MapPath("/img/" + filename)))
{
using (Bitmap bitmap=new Bitmap(width,height))
{
using (Graphics g=Graphics.FromImage(bitmap))
{
//g.InterpolationMode = InterpolationMode.High;
//g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawImage(oldImg, new Rectangle(0, 0, width, height), new Rectangle(left, top, width, height), GraphicsUnit.Pixel);
g.Save();
}
bitmap.Save(context.Server.MapPath("/img/cut/" + filename));

}
}
context.Response.Write("/img/cut/" + filename);
}


具体实现结果如下:

界面:



上传图片: 图片截取:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐