[ASP.NET]使用uploadify上传图片,并在uploadify按钮上生成预览图
目录
需求
项目中有用到uploadify上传插件,给的原型就是上传成功后替换原来的图片。没办法需求在那儿,也不能修改需求吧,只能想办法解决问题了。
主要代码
修改uploadify样式:
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/ .uploadify {
position: relative;
margin-bottom: 1em;
color:blue;
} /*.uploadify-button {
background-color: #505050;
background-image: linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -o-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -moz-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -webkit-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -ms-linear-gradient(bottom, #505050 0%, #707070 100%);
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, #505050),
color-stop(1, #707070)
);
background-position: center top;
background-repeat: no-repeat;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
border-radius: 30px;
border: 2px solid #808080;
color: #FFF;
font: bold 12px Arial, Helvetica, sans-serif;
text-align: center;
text-shadow: 0 -1px 0 rgba(0,0,0,0.25);
width: 100%;
}
.uploadify:hover .uploadify-button {
background-color: #606060;
background-image: linear-gradient(top, #606060 0%, #808080 100%);
background-image: -o-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -moz-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -webkit-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -ms-linear-gradient(top, #606060 0%, #808080 100%);
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, #606060),
color-stop(1, #808080)
);
background-position: center bottom;
}*/
.uploadify-button.disabled {
background-color: #D0D0D0;
color: #808080;
}
.uploadify-queue {
margin-bottom: 1em;
}
.uploadify-queue-item {
background-color: #F5F5F5;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
font: 11px Verdana, Geneva, sans-serif;
margin-top: 5px;
max-width: 350px;
padding: 10px;
}
.uploadify-error {
background-color: #FDE5DD !important;
}
.uploadify-queue-item .cancel a {
background: url('../img/uploadify-cancel.png') 0 0 no-repeat;
float: right;
height: 16px;
text-indent: -9999px;
width: 16px;
}
.uploadify-queue-item.completed {
background-color: #E5E5E5;
}
.uploadify-progress {
background-color: #E5E5E5;
margin-top: 10px;
width: 100%;
}
.uploadify-progress-bar {
background-color: #0099FF;
height: 3px;
width: 1px;
}
将uploadify默认样式注释。
上传按钮代码:
<input type="hidden" id="hdId" name="name" value="1" />
<img src="../images/logo/logo.png" alt="图标" id="imgUpload" />
uploadify是基于flash的上传插件,在客户端生成的是object对象。
通过上图可知,设置的img上传按钮在客户端由div代替,id变为imgUpload-button。知道id了就好办了。
js代码:
<link href="JS/uploadify/css/uploadify.css" rel="stylesheet" />
<script type="text/javascript" src="JS/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="JS/uploadify/js/uploadify3.2.1/jquery.uploadify.js"></script>
<script type="text/javascript">
$(function () {
//初始化上传插件
InitUploadify("imgUpload");
});
function InitUploadify(id) { //上传插件初始化方法
$('#' + id).uploadify({
//选择文件后是否自动上传,默认为true
'auto': true,
//单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值 上传大文件 可参考使用手册说明
'fileSizeLimit': '2MB',
'width': 40,
'height': 40,
//文件描述
'fileTypeDesc': 'Files',
//允许上传的文件类型 以分号分割
'fileTypeExts': '*.gif; *.jpg; *.png;',
//请求方式"get"或者"post",默认为"post"
'method': 'post',
//是否允许同时选择多个文件,默认为true
'multi': false,
'buttonImage': '../images/logo/logo.png',
//队列的ID,一个存放上传文件div的ID
'queueID': 'fileQueue',
//FLash文件路径
'swf': '/JS/uploadify/js/uploadify3.2.1/uploadify.swf',
'onUploadStart': function (file) {
//传递参数
$("#" + id).uploadify("settings", "formData", { 'strId': $("#hdId").val() });
},
//上传文件处理后台页面
'uploader': 'UploadImgHandler.ashx',
//重写错误事件,否则在关闭自定义错误提示框后,扔弹出默认的英文信息
'overrideEvents': ['onSelectError', 'onDialogClose'],
//返回一个错误,选择文件的时候触发
'onSelectError': function (file, errorCode, errorMsg) {
switch (errorCode) {
case -100:
alert("上传的文件数量已经超出系统限制的" + $("#" + id).uploadify('settings', 'queueSizeLimit') + "个文件!");
break;
case -110:
alert("文件 [" + file.name + "] 大小超出系统限制的" + $("#" + id).uploadify('settings', 'fileSizeLimit') + "大小!");
break;
case -120:
alert("文件 [" + file.name + "] 大小异常!");
break;
case -130:
alert("文件 [" + file.name + "] 类型不正确!");
break;
}
},
//检测FLASH失败调用
'onFallback': function () {
alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
},
//上传成功后触发,每个文件都触发
'onUploadSuccess': function (file, data, response) {
var result = eval('(' + data + ')');
if (result.imgSrc != "0") {
//置换按钮的背景图,uploadify在客户端生成的id为imgUpload-button
$("#imgUpload-button").css("background-image", "url('" + result.imgSrc + "')").attr({ "src": result.imgSrc });
} else {
alert("上传失败");
}
} });
}
</script>
需要注意,上面采用了自定义错误提示,需要
//重写错误事件,否则在关闭自定义错误提示框后,扔弹出默认的英文信息
'overrideEvents': ['onSelectError', 'onDialogClose'],
不然在弹出自定义的错误信息后,关闭错误信息仍会出现英文错误信息。
将该句注释后,测试结果:
单击确定后
所以在自定义错误提示信息时需要重写事件。
['onSelectError', 'onDialogClose']
接收上传图片的一般处理程序代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web; namespace Wolfy.UploadifyImageDemo
{
/// <summary>
/// UploadImgHandler 的摘要说明
/// </summary>
public class UploadImgHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//获取上传的文件
HttpPostedFile httpPostedFile = context.Request.Files["Filedata"]; //如果接收到文件则httpPostedFile不为null,则对上传的文件进行处理,否则向客户端返回0
if (httpPostedFile != null)
{
//获取文件名
string strfileName = httpPostedFile.FileName; //获取扩展名
string strExt = Path.GetExtension(strfileName); //允许上传的文件类型
string[] strExts = { ".jpg", ".png", ".gif" }; //如果上传的文件类型,在被允许的类型中,则保存,否则向客户端输出“不允许上传”的信息提示。
if (strExts.Contains(strExt))
{
string strSaveName = string.Empty;
string strSavePath = ConvertImageByWH(context, httpPostedFile.InputStream, , , strExt, out strSaveName); string strJson = " { 'imgSrc': '" + strSavePath + "'} ";
//将文件的保存的相对路径输出到客户端
context.Response.Write(strJson); }
else
{
context.Response.Write("{'imgSrc':'0'}");
}
}
}
/// <summary>
/// 按照给定的宽高对图片进行压缩
/// </summary>
/// <param name="byteImg">图片字节流</param>
/// <param name="intImgCompressWidth">压缩后的图片宽度</param>
/// <param name="intImgCompressHeight">压缩后的图片高度</param>
/// <param name="strExt">扩展名</param>
/// <param name="strSaveName">保存后的名字</param>
/// <returns>压缩后的图片相对路径</returns>
private string ConvertImageByWH(HttpContext context, Stream stream, int intImgCompressWidth, int intImgCompressHeight, string strExt, out string strSaveName)
{
//从输入流中获取上传的image对象
using (System.Drawing.Image img = System.Drawing.Image.FromStream(stream))
{
//根据压缩比例求出图片的宽度
int intWidth = intImgCompressWidth / intImgCompressHeight * img.Height;
int intHeight = img.Width * intImgCompressHeight / intImgCompressWidth;
//画布
using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img, new Size(intImgCompressWidth, intImgCompressHeight)))
{
//在画布上创建画笔对象
using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
{
//将图片使用压缩后的宽高,从0,0位置画在画布上
graphics.DrawImage(img, , , intImgCompressWidth, intImgCompressHeight);
//创建保存路径
string strSavePath = "/images/logo/"; //如果保存目录不存在,则创建
if (!Directory.Exists(context.Server.MapPath(strSavePath)))
{
Directory.CreateDirectory(context.Server.MapPath(strSavePath));
}
//定义新的文件名
string strfileNameNoExt = string.Empty;
//接收参数
string strId = context.Request.Params["strId"];
if (!string.IsNullOrEmpty(strId))
{
if (strId == "")
{
//定义新的文件名
strfileNameNoExt = Guid.NewGuid().ToString();
}
} strSaveName = strfileNameNoExt + strExt;
//添加时如果图片已经存在则删除
if (File.Exists(context.Server.MapPath(strSavePath) + strSaveName))
{
File.Delete(context.Server.MapPath(strSavePath) + strSaveName);
}
//保存文件
bitmap.Save(context.Server.MapPath(strSavePath) + strSaveName);
return strSavePath + strSaveName;
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
测试结果:
默认:
上传成功后:
总结
在项目中多少会用到一些插件,但是又不能完全适应需求,这时就需要对其进行定制的修改,这时候F12还是很管用的。
[ASP.NET]使用uploadify上传图片,并在uploadify按钮上生成预览图的更多相关文章
- ASP.NET工作笔记之一:图片上传预览及无刷新上传
转自:http://www.cnblogs.com/sibiyellow/archive/2012/04/27/jqueryformjs.html 最近项目里面涉及到无刷新上传图片的功能,其实也就是上 ...
- jquery实现上传图片及图片大小验证、图片预览效果代码
jquery实现上传图片及图片大小验证.图片预览效果代码 jquery实现上传图片及图片大小验证.图片预览效果代码 上传图片验证 */ function submit_upload_picture() ...
- [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有真相,总有一款适合你!
引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案一 直接在浏览器中打开Office文档在页面上的链接.会弹出如下窗口: 优点:主流浏览器都支持. 缺点: ...
- Asp.net实现同页面内多图片自动上传并带预览显示
FileUpload控件实现单按钮图片自动上传并带预览显示 1.实现原理: 此方法适合针对有后台生成的图片相关内容,例如购物网站商品展示页面中的封面图片,图片的数量由后台访问数据库,并加载到页面.这种 ...
- 转载: Asp.net常见word,excel,ppt,pdf在线预览方案
参考链接: http://www.cnblogs.com/wolf-sun/p/3569960.html
- [Asp.net]常见word,excel,ppt,pdf在线预览方案(转)
引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案一 直接在浏览器中打开Office文档在页面上的链接.会弹出如下窗口: 优点:主流浏览器都支持. 缺点: ...
- [Asp.net]使用flexpaper+swftools大文件分页转换实现在线预览
引言 之前总结了在线预览几种常见解决方案,可以戳这里: http://www.cnblogs.com/wolf-sun/p/3569960.html http://www.cnblogs.com/wo ...
- js:s上次预览,上传图片预览,图片上传预览
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 关于asp.net mvc中 weiui gallery中IOS 下不显示预览图片问题的解决方式
IOS 下面不显示预览. 结果去掉了红框中的缓存部分 就可以显示了 备忘,也帮助一下需要的朋友 @*<meta http-equiv="pragma" content=&qu ...
随机推荐
- Linux下使用ping出现destination is unreachable的问题可能性
ping时出现request time out和destination is unreachable request time out是指icmp包发出后,长时间没有回应,所以会产生request t ...
- php curl 抓取
<?php set_time_limit(0); function curl_multi($urls) { if (!is_array($urls) or count($urls) == 0) ...
- IOS-百度地图API用点生成线路、导航、自定义标注 2013年11月更新
IOS百度地图API开发自定义气泡,点击气泡自动生成路线,以及拖拽IOS百度地图开发POISearch搜索附近停车场,附近加油站IOS百度地图视角跳到用户当前位置IOS百度地图开发实时路况IOS开发百 ...
- 打开/查找xcode6的沙盒地目录
用以下代码 打开沙盒目录 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainM ...
- Html基础知识详解
一定要做的符合客户要求,不是自己认为对的. 一.基础标签 1.1 大小颜色位置 <!DOCTYPE HTML> <html> <head> <meta htt ...
- jquery css 主菜单样式的跳转
想要实现的效果事实上是挺常见的那种:网页的主菜单一開始有一种默认的样式(如A样式),当鼠标经过某一菜单项时.此菜单项会套用一种样式(如B样式),当鼠标点击某一菜单项时.当前菜单项会套用B样式,其余菜单 ...
- Spring事务为什么不会自动回滚?Spring事务怎样才会自动回滚?事务自动回滚条件及手动回滚
原文:https://blog.csdn.net/qq_32331073/article/details/76508147 更多Spring事务问题请访问链接:Spring事务回滚问题疑难详解 在此, ...
- python笔记19-获取当前运行函数名称和类方法名称
前言 写完代码之后,一般为了方便查看日志,可以在日志输出中加入当前运行的函数名称或类和方法名称,以便于代码报错的时候能快速找到报错的是哪个函数或方法. 那么如何获取当前运行函数(或方法)的名称呢? 获 ...
- fatal error: sys/cdefs.h: No such file or directory
sudo apt-get install g++-multilib
- JAVA单例MongoDB工具类
我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用. 没用Spring Data.Morphia等框架是为了减少学习.维护成本,另外自己直接JDBC方式的话可以 ...