之前写过几篇文件上传,那些都不错。今天小编带领大家体会一种新的上传方法,及使用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插件实现文件异步上传和头像截取的更多相关文章

  1. jQuery插件之ajaxFileUpload异步上传

    介绍 AjaxFileUpload.js 是一个异步上传文件的jQuery插件,原理是创建隐藏的表单和iframe然后用JS去提交,获得返回值. 下载地址: http://files.cnblogs. ...

  2. 【转】JQuery插件ajaxFileUpload 异步上传文件(PHP版)

    前几天想在手机端做个异步上传图片的功能,平时用的比较多的JQuery图片上传插件是Uploadify这个插件,效果很不错,但是由于手机不支持flash,所以不得不再找一个文件上传插件来用了.后来发现a ...

  3. JQuery插件ajaxFileUpload 异步上传文件(PHP版)

    太久没写博客了,真的是太忙了.善于总结,进步才会更快啊.不多说,直接进入主题. 前几天想在手机端做个异步上传图片的功能,平时用的比较多的JQuery图片上传插件是Uploadify这个插件,效果很不错 ...

  4. 适用于各浏览器支持图片预览,无刷新异步上传js插件

    文件上传无疑是web应用中一个非常常用的功能,不管是PHP.jsp还是aspx.mvc等都会需要文件上传,但是众所周知当使用自带的文件上传功能时总会出现页面刷新的情况.当然现在有了html5这个好东西 ...

  5. 使用ajax异步上传文件或图片(配合php)

    //html代码 <form enctype="multipart/form-data" id="upForm"> <input type=& ...

  6. ajax 异步上传视频带进度条并提取缩略图

    最近在做一个集富媒体功能于一身的项目.需要上传视频.这里我希望做成异步上传,并且有进度条,响应有状态码,视频连接,缩略图. 服务端响应 { "thumbnail": "/ ...

  7. sae storage 使用uploadify插件进行文件批量上传

    uploadify插件在文件上传方面还是很不错的,这不我需要往sae 的storage上上传文件,就用了它.下面我就分享一下如何实现的吧.我们先到官网下载最新的uploadify最新的插件包.在页面中 ...

  8. JQUery利用Uploadify插件实现文件异步上传(十一)

    一:简介: Uploadify是JQuery的一个上传插件,实现的效果非常好,带进度显示 ,且Ajax异步,能一次性上传多个文件,功能强大,使用简单 1.支持单文件或多文件上传,可控制并发上传的文件数 ...

  9. 视频大文件分片上传(使用webuploader插件)

    背景 公司做网盘系统,一直在调用图片服务器的接口上传图片,以前写的,以为简单改一改就可以用 最初要求 php 上传多种视频格式,支持大文件,并可以封面截图,时长统计 问题 1.上传到阿里云服务器,13 ...

随机推荐

  1. Windows下Memcached安装与配置实例

    环境声明: 服务器: Windows Server 2008r2: Memcached: Memcached 64-bit for Windows(64位) From: http://www.urie ...

  2. reStructuredText(rst)快速入门语法说明

    reStructuredText 是扩展名为.rst的纯文本文件,含义为"重新构建的文本"",也被简称为:RST或reST:是Python编程语言的Docutils项目的 ...

  3. js正则表达式校验非零的正整数:^[1-9]\d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^\+?[1-9][0-9]*$

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. Delphi_01_控制台版HelloWorld

    对于Windows下的控制台编程,我相信很多人都不陌生.而C语言开始的著名的“Hello world”程序基本是学习编程的第一步.我想对于 RAD开发,大家熟悉的一般都是GUI编程,而对于consol ...

  5. 《连载 | 物联网框架ServerSuperIO教程》- 5.轮询通讯模式开发及注意事项。附:网友制作的类库说明(CHM)

    1.C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 <连载 | 物联网框架ServerSuperIO教程>1.4种通讯模式机制. <连载 | 物联网框架Serve ...

  6. 深入理解js的变量提升和函数提升

    一.变量提升 在ES6之前,JavaScript没有块级作用域(一对花括号{}即为一个块级作用域),只有全局作用域和函数作用域.变量提升即将变量声明提升到它所在作用域的最开始的部分.上个简历的例子如: ...

  7. css基础

    一. web标准化 (1).内容与样式,行为分离 (2).html用来定义语义内容,以及内容的结构 (xhtml) (3).xhtml标准 a.xhtml 必须强制指定文档类型 DocType,HTM ...

  8. RichText

    RichText 效果 特点 1.按照需要调节部分字体的颜色 2.调节段落的行间距,字间距 源码 github:https://github.com/makingitbest/RichText 细节 ...

  9. LaunchScreen.storyboard启动图遇到的坑

    Xcode有时候在LaunchScreen.storyBoard中修改了启动图片之后,运行却没有效果,直接白屏,而往storyboard中拖插件是可以显示的,设置成Assets.xcassets中的其 ...

  10. Listview的Item中有CheckBox、Button等的焦点处理

    ListView的item布局中有CheckBox.Button等会获取焦点的控件会抢走焦点,造成ListView的item点击事件相应不了. 解决方法:控件设置 android:clickable= ...