文件上传之——用SWF插件实现文件异步上传和头像截取
之前写过几篇文件上传,那些都不错。今天小编带领大家体会一种新的上传方法,及使用Flash插件实现文件上传。
使用Flash的好处就是可以解决浏览器兼容性问题。之前我写的一个快捷复制功能也是利用的Flash。
最近一直在用MVC,所以还是以MVC举例;先来张效果图:
UploadIndex2.cshtml代码:
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title>上传</title>
<script src="~/SWFUpload/swfupload.js" type="text/javascript"></script>
<script src="~/SWFUpload/handlers.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "@Url.Action("HandlerUpload2","Home")",//上传路径
post_params: {
"ASPSESSID": "<@Session.SessionID>"
}, // File Upload Settings
file_size_limit: "5 MB",
file_types: "*.jpg;*.gif",
file_types_description: "JPG Images",
file_upload_limit: , // 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: showData,
upload_complete_handler: uploadComplete, // Button settings
button_image_url: "/SWFUpload/images/XPButtonNoText_160x22.png",//设置按钮图片,注意要是连续的四张
button_placeholder_id: "spanButtonPlaceholder",//设置按钮id
button_width: ,
button_height: ,
button_text: '<span class="button">请选择上传图片 <span class="buttonSmall">(5 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: ,
button_text_left_padding: , // 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 showData(file, serverData) {
$("#imgSrc").attr("src", serverData);
}
</script>
</head>
<body>
<form id="form1"> <div id="content"> <div id="swfu_container" style="margin: 0px 10px;">
<div>
<span id="spanButtonPlaceholder"></span> <!--注意:这个ID要和上面的一致-->
</div> <img id="imgSrc" /><!---在这里显示上传的图片,这个插件采用的为异步上传-->
</div>
</div>
</form>
</body>
</html>
后端代码:
public ActionResult UploadIndex2()
{
return View();
} [HttpPost]
public ActionResult HandlerUpload2()
{
HttpPostedFileBase file = Request.Files["Filedata"];//获取文件数据.
string fileName = Path.GetFileName(file.FileName);//获取文件名.
string fileExt = Path.GetExtension(fileName); //获取文件类型
string fullDir = "";
if (fileExt == ".jpg")
{
string dir = "/UploadImage/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "/";
Directory.CreateDirectory(Path.GetDirectoryName(Server.MapPath(dir)));//如果没有文件目录,创建.
fullDir = dir + OnLineBooks.App.Common.WebCommon.GetStreamMD5(file.InputStream) + fileExt;//构建了一个完整路径,并且以文件流的MD5值作为文件的名称,解决了文件名称重名问题。
file.SaveAs(Server.MapPath(fullDir));//文件保存
}
return Content(fullDir);//返回图片路径
}
SWFUpload文件下载链接:http://pan.baidu.com/s/1c2xIf5Y密码:wphd
上面提到了图片上传,接下来小编带大家实现图像截取,先上图:
前台实现:
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>UploadIndex3</title>
<link href="~/Content/themes/ui-lightness/jquery-ui-1.8.2.custom.css" rel="stylesheet" />
<script src="~/SWFUpload/swfupload.js" type="text/javascript"></script>
<script src="~/SWFUpload/handlers.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/SWFUpload/jquery-ui-1.8.2.custom.min.js"></script>
@*<script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>*@
<script type="text/javascript">
var swfu;
window.onload = function () {
swfu = new SWFUpload({
// Backend Settings
upload_url: "@Url.Action("Cut_upload", "Home")?action=up",
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, // 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: showData,
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
});
}
//上传成功以后执行该方法.
var data;
function showData(file, serverData) {
//一:创建一个DIV,通过该DIV确定出要截取大小与范围.(实现DIV的拖动与调整大小.)
//首先将上传成功的图像作为divContent的背景图像.
data = serverData.split(':');
if (data[0] == "ok") {
//设置图片的高度与宽度,注意单位.px
$("#divContent").css("backgroundImage", "url(" + data[1] + ")").css("width", data[2] + "px").css("height", data[3] + "px");
}
}
//拖动红色DIV并且可以调整大小.
$(function () {
$("#divCut").resizable({
containment: "#divContent"
}).draggable({ containment: "parent" }); //设置拖动
$("#btnCut").click(function () {
CutImage();//截取头像
});
});
function CutImage() {
//offset():获取元素的绝对坐标 top:纵坐标
var y = $("#divCut").offset().top - $("#divContent").offset().top;//纵坐标
var x = $("#divCut").offset().left - $("#divContent").offset().left;
var width = $("#divCut").width(); //宽度.
var height = $("#divCut").height();
//将上面的数据发送到服务端.
$.post("@Url.Action("Cut_upload", "Home")", { "action": "cut", "x": parseInt(x), "y": parseInt(y), "width": parseInt(width), "height": parseInt(height), "imgUrl": data[1] }, function (data) {
$("#imgUrl").attr("src", data);
}) } </script> </head>
<body>
<form id="form1">
<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>
<div id="divContent" style="width:300px; height:300px">
<div id="divCut" style="width:100px; height:100px; border:1px solid red"></div>
</div>
<input type="button" value="头像截取" id="btnCut" />
<img id="imgUrl" />
</div>
</form>
</body>
</html>
后台实现:
/// <summary>
/// 截取图像
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult Cut_upload()
{
string action = Request["action"];
if (action == "up")//上传
{
HttpPostedFileBase file = Request.Files["Filedata"];//获取文件数据.
//获取文件名.
string fileName = Path.GetFileName(file.FileName);
//获取文件类型
string fileExt = Path.GetExtension(fileName);
if (fileExt == ".jpg")
{
//获取上传的图片的流(文件内容),创建一个Image.所以Image的高度与宽度实际上就是上传图片的高度与宽度.
using (Image img = Image.FromStream(file.InputStream))
{
file.SaveAs(Server.MapPath("/UploadImage/" + fileName));
return Content("ok:/UploadImage/" + fileName + ":" + img.Width + ":" + img.Height);
}
}
}
else if (action == "cut")//头像截取
{
//1:接收截取头像范围的数据
int x = Convert.ToInt32(Request.Form["x"]);
int y = Convert.ToInt32(Request.Form["y"]);
int width = Convert.ToInt32(Request.Form["width"]);
int height = Convert.ToInt32(Request.Form["height"]);
string imgUrl = Request.Form["imgUrl"];
//2:创建画布,然后将指定范围的图像画到画布上,最后保存画布.
using (Bitmap map = new Bitmap(width, height))//画布的大小与截取的图像大小一致
{
//为画布创建了一个画笔.
using (Graphics g = Graphics.FromImage(map))
{
//为上传成功的头像创建一个Image
using (Image img = Image.FromFile(Server.MapPath(imgUrl)))
{//将图像画到画布上.
//第一参数:表示对哪张图片进行操作.
//二:画多么大
//三:画哪一部分.
g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
string imgName = Guid.NewGuid().ToString().Substring(0, 8);
map.Save(Server.MapPath("/UploadImage/" + imgName + ".jpg"));//将Bitmap保存成图片文件
return Content("/UploadImage/" + imgName + ".jpg");
}
}
}
}
return Content("");
}
zj。。。
文件上传之——用SWF插件实现文件异步上传和头像截取的更多相关文章
- jQuery插件之ajaxFileUpload异步上传
介绍 AjaxFileUpload.js 是一个异步上传文件的jQuery插件,原理是创建隐藏的表单和iframe然后用JS去提交,获得返回值. 下载地址: http://files.cnblogs. ...
- 【转】JQuery插件ajaxFileUpload 异步上传文件(PHP版)
前几天想在手机端做个异步上传图片的功能,平时用的比较多的JQuery图片上传插件是Uploadify这个插件,效果很不错,但是由于手机不支持flash,所以不得不再找一个文件上传插件来用了.后来发现a ...
- JQuery插件ajaxFileUpload 异步上传文件(PHP版)
太久没写博客了,真的是太忙了.善于总结,进步才会更快啊.不多说,直接进入主题. 前几天想在手机端做个异步上传图片的功能,平时用的比较多的JQuery图片上传插件是Uploadify这个插件,效果很不错 ...
- 适用于各浏览器支持图片预览,无刷新异步上传js插件
文件上传无疑是web应用中一个非常常用的功能,不管是PHP.jsp还是aspx.mvc等都会需要文件上传,但是众所周知当使用自带的文件上传功能时总会出现页面刷新的情况.当然现在有了html5这个好东西 ...
- 使用ajax异步上传文件或图片(配合php)
//html代码 <form enctype="multipart/form-data" id="upForm"> <input type=& ...
- ajax 异步上传视频带进度条并提取缩略图
最近在做一个集富媒体功能于一身的项目.需要上传视频.这里我希望做成异步上传,并且有进度条,响应有状态码,视频连接,缩略图. 服务端响应 { "thumbnail": "/ ...
- sae storage 使用uploadify插件进行文件批量上传
uploadify插件在文件上传方面还是很不错的,这不我需要往sae 的storage上上传文件,就用了它.下面我就分享一下如何实现的吧.我们先到官网下载最新的uploadify最新的插件包.在页面中 ...
- JQUery利用Uploadify插件实现文件异步上传(十一)
一:简介: Uploadify是JQuery的一个上传插件,实现的效果非常好,带进度显示 ,且Ajax异步,能一次性上传多个文件,功能强大,使用简单 1.支持单文件或多文件上传,可控制并发上传的文件数 ...
- 视频大文件分片上传(使用webuploader插件)
背景 公司做网盘系统,一直在调用图片服务器的接口上传图片,以前写的,以为简单改一改就可以用 最初要求 php 上传多种视频格式,支持大文件,并可以封面截图,时长统计 问题 1.上传到阿里云服务器,13 ...
随机推荐
- 把PDF的底色改成护眼色,这样读起文章来就不是很累了······
PDF格式背景改变方法如下: 打开PDF 点击 编辑 ->首选项->辅助工具->选中"替换文档颜色"和" 自定义颜色"->将背景颜色改成 ...
- enumerate用法总结-Python 3
enumerate()说明 enumerate()是python的内置函数 enumerate在字典上是枚举.列举的意思 对于一个可迭代的(iterable)/可遍历的对象(如列表.字符串),enum ...
- 使用do{ } while(0)的好处
经常看到好多程序,尤其是linux相关的,使用do{}while(0)的写法,很明显内部程序最多只能执行一次,这样写的原因是什么呢?个人认为主要的原因是,如果不使用do{}while(0),那么当一个 ...
- jvm内存溢出分析
概述 jvm中除了程序计数器,其他的区域都有可能会发生内存溢出 内存溢出是什么? 当程序需要申请内存的时候,由于没有足够的内存,此时就会抛出OutOfMemoryError,这就是内存溢出 内存溢出和 ...
- Android经典的设计模式
[单例模式][Build模式][原型模式][工厂模式][策略模式][状态模式][责任链模式][解释器模式][命令模式][观察者模式][备忘录模式][迭代器模式] [模板方法模式][访问者模式][中介者 ...
- 【搬砖】安卓入门(4)- Java开发编程基础--数组
05.01_Java语言基础(数组概述和定义格式说明)(了解) A:为什么要有数组(容器) 为了存储同种数据类型的多个值 B:数组概念 数组是存储同一种数据类型多个元素的集合.也可以看成是一个容器. ...
- Objective-C之KVC、KVO
1,KVC(键值编码) Key Value Coding 1.1在C#中,可以通过字符串反射来获取对象,从而对对象的属性进行读写,Object-C中有同样的实现,通过字符串(属性名词)对对象的属性进 ...
- git推送本地分支到远程分支
场景 有时候我们开发需要开一个分支,这样可以有效的并行开发. 开分支有两种方式: 一种是在远程开好分支,本地直接拉下来; 一种是本地开好分支,推送到远程. 远程先开好分支然后拉到本地 git chec ...
- Hive-0.x.x - Enviornment Setup
All Hadoop sub-projects such as Hive, Pig, and HBase support Linux operating system. Therefore, you ...
- Python学习笔记3-字符串
格式化字符串/复合字段名 >>> import humansize >>> si_suffixes = humansize.SUFFIXES[1000] >& ...