‘壹’ 当点击带+的图片时,弹出手机相册,可以选择手机相册内的图片上传,代码如何写怎么实现
首先需要引用 js 和css
<!--上传控件-->
2<scriptsrc="query.form.min.js"></script>
3<linkhref="Img_List.css"rel="stylesheet"/>
4<scriptsrc="Img_List.js"></script>
Img_List.js 如下:
///<referencepath="../../script/jquery-1.8.0.min.js"/>
//显示
functionimgshow(obj){
//$(obj).find("a").show();
}
//隐藏
functionimghide(obj){
//$(obj).find("a").hide();
}
//上传
functionupload(){
$("#FileLoad").click();
}
//删除
functionimgdel(listId,FileId,hfId){
$.post("/CommonMole/ashx/public.ashx?action=DelMessageImg&Files="+$("#"+hfId).val(),function(result){
if(result!="ok")
$.messager.alert("消息提示","删除失败!");
});
varhtml="<li><imgsrc="/Themes/Images/jia.jpg"style="height:80px;width:80px;"/><inputtype="file"id=""+FileId+""class="input"onchange="ImgUpload('"+FileId+"','"+hfId+"','"+listId+"');"name=""+FileId+""/></li>"
$("#"+listId).html(html);
}
//添加成功
functionimgaddhtml(data,code,listId,fileId,hfId){
varlist=data.split(',');
varhtml="<lionmouseover="imgshow(this)"onmouseout="imghide(this);">";
html+="<astyle="height:80px;width:80px;"href=""+list[0]+""target="_blank"><imgsrc=""+list[0]+""imgs=""+list[0]+""code=""+code+""/></a><spanonclick="imgdel('"+listId+"','"+fileId+"','"+hfId+"')"></span></li>";
$("#"+listId).html(html);
}
//图片文件上传
//uppath上传空间id
//上传成功存放的图片路径的隐藏域id
//listId显示图片的区域id
functionImgUpload(uppath,hndimg,listId){
varsendUrl="/CommonMole/ashx/Upload_Ajax.ashx?action=SingleFile&IsThumbnail=1&UpFilePath="+uppath;
//开始提交
$("#form1").ajaxSubmit({
beforeSubmit:function(formData,jqForm,options){
//alert(1);
},
success:function(data,textStatus){
varlist=$("#"+hndimg).val();
$("#"+hndimg).val(data.msgbox);
imgaddhtml(data.msgbox,0,listId,uppath,hndimg);
},
error:function(data,status,e){
alert("上传失败!");
},
url:sendUrl,
type:"post",
dataType:"json",
timeout:600000
});
};
Img_List.css如下:
.img_list{margin:0px;padding:0px;overflow:hidden;}
.img_listul,.img_listulli{margin:0px;padding:0px;}
.img_listulli{float:left;list-style:none;position:relative;margin:5px0px0px5px;}
.img_listullispan
{position:absolute;top:3px;right:3px;width:16px;height:16px;opacity:0.6;filter:alpha(opacity=60);margin:0002px;
vertical-align:top;background:url('/Themes/Images/panel_tools.png')no-repeat-16px0px;}
.img_listulliimg{width:80px;height:80px;cursor:pointer;position:relative;z-index:0;}
.img_listulli.input{width:80px;height:80px;cursor:pointer;position:relative;left:-100px;vertical-align:top;margin:0px;padding:0px;opacity:0;filter:alpha(opacity=0);}
panel_tools.png 如下:
#region上传单文件处理===================================
46privatevoidSingleFile(HttpContextcontext)
47{
48
49string_refilepath=context.Request.QueryString["ReFilePath"];//取得返回的对象名称
50string_upfilepath=context.Request.QueryString["UpFilePath"];//取得上传的对象名称
51string_delfile=context.Request.QueryString[_refilepath];
52HttpPostedFile_upfile=null;
53try
54{
55_upfile=context.Request.Files[_upfilepath];
56}
57catch(Exceptione)
58{
59context.Response.Write("{"msg":"0","msgbox":"上传文件过大!"}");
60context.Response.End();
61}
62bool_iswater=false;//默认不打水印
63bool_isthumbnail=false;//默认不生成缩略图
64bool_isimage=false;
65
66if(context.Request.QueryString["IsWater"]=="1")
67_iswater=true;
68if(context.Request.QueryString["IsThumbnail"]=="1")
69_isthumbnail=true;
70if(context.Request.QueryString["IsImage"]=="1")
71_isimage=true;
72
73if(_upfile==null)
74{
75context.Response.Write("{"msg":"0","msgbox":"请选择要上传文件!"}");
76return;
77}
78UpLoapFiles=newUpLoad();
79stringmsg=upFiles.fileSaveAs(_upfile,_isthumbnail,_iswater,_isimage);
80//删除已存在的旧文件
81Utils.DeleteUpFile(_delfile);
82//返回成功信息
83context.Response.Write(msg);
84
85context.Response.End();
86}
87#endregion
101publicstringfileSaveAs(HttpPostedFilepostedFile,boolisThumbnail,boolisWater,bool_isImage,bool_isReOriginal)
102{
103try
104{
105stringfileExt=Utils.GetFileExt(postedFile.FileName);//文件扩展名,不含“.”
106stringoriginalFileName=postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"")+1);//取得文件原名
107stringfileName=Utils.GetRamCode()+"."+fileExt;//随机文件名
108stringdirPath=GetUpLoadPath();//上传目录相对路径
109
110//检查文件扩展名是否合法
111if(!CheckFileExt(fileExt))
112{
113return"{"msg":"0","msgbox":"不允许上传"+fileExt+"类型的文件!"}";
114}
115//检查是否必须上传图片
116if(_isImage&&!IsImage(fileExt))
117{
118return"{"msg":"0","msgbox":"对不起,仅允许上传图片文件!"}";
119}
120//检查文件大小是否合法
121if(!CheckFileSize(fileExt,postedFile.ContentLength))
122{
123return"{"msg":"0","msgbox":"文件超过限制的大小啦!"}";
124}
125//获得要保存的文件路径
126stringserverFileName=dirPath+fileName;
=dirPath+"small_"+fileName;
128stringreturnFileName=serverFileName;
129//物理完整路径
130stringtoFileFullPath=Utils.GetMapPath(dirPath);
131//检查有该路径是否就创建
132if(!Directory.Exists(toFileFullPath))
133{
134Directory.CreateDirectory(toFileFullPath);
135}
136//保存文件
137postedFile.SaveAs(toFileFullPath+fileName);
138//如果是图片,检查图片尺寸是否超出限制
139if(IsImage(fileExt))
140{
141Thumbnail.MakeThumbnailImage(toFileFullPath+fileName,toFileFullPath+fileName,3000,3000);
142}
143//是否生成缩略图
144if(IsImage(fileExt)&&isThumbnail)
145{
146Thumbnail.MakeThumbnailImage(toFileFullPath+fileName,toFileFullPath+"small_"+fileName,150,150,"R");
147//returnFileName+=","+serverThumbnailFileName;//返回缩略图,以逗号分隔开
148}
149
166/
171return"{"msg":"1","msgbox":""+returnFileName+""}";
172}
173catch
174{
175return"{"msg":"0","msgbox":"上传过程中发生意外错误!"}";
176}
177}
‘贰’ js/jquery上传图片的问题
function showImage(fileid,imgid,atagID){
var ext = "_0";
var thumb = $('img#'+imgid);
var litbox = $('a#'+atagID);
var img1path = document.getElementById("img1path");;
if($('.onTeedaError').length>0){
//img1path.value="";
}
var messages =document.getElementById("messages");
if(messages!=null){
//img1path.value="";
}
new AjaxUpload(fileid, {
action: '../../PdfChangeImgUploadServlet?pdfNameEnd=_PERT',
name: ext,
onSubmit: function(file, extension) {
extension=extension.toLowerCase();
if(extension=="pdf")
{
$("#photoError").hide();
$.blockUI({
message: $('span#displayBox'),
css: {
border: 'none',
width: '270px',
}
});
}else{
$("#photoError").show();
return false;
}
},
onComplete: function(file, response) {
$('.pdfImg').remove();
$('#pfont').hide();
$.unblockUI();
var res = eval('('+response+');');
var timestemp = new Date().getTime();
var srcStr = res['srcStr'];
$('#addImg').val(res['srcStr']);
var imgWidth = res['w'] + "px";
var imgHeight = res['h'] + "px";
$("#addImgWidth").val(imgWidth);
$("#addImgHeight").val(imgHeight);
var str = "";
var arr = [];
arr = srcStr.split(",");
$('#imgFile').attr("value",srcStr);
for(var i=0;i<arr.length;i++){
var jpgsrc = arr[i] + '?'+ timestemp;
if(i == 0){
str=str+"<a class=\"pdfImg\" style=\"margin-left:10px;\" href="+jpgsrc+" rel=\"lightbox"+timestemp+"\">";
str=str+"<img class=\"jpgImgFont\" src="+jpgsrc+" style=\"vertical-align:middle;cursor:pointer;width:"+ imgWidth +";height:"+ imgHeight +" \" />";
str=str+"</a>";
} else {
str=str+"<a class=\"pdfImg\" style=\"margin-left:10px;display:none;\" href="+jpgsrc+" rel=\"lightbox"+timestemp+"\">";
str=str+"<img class=\"jpgImgFont\" src="+jpgsrc+" style=\"vertical-align:middle;cursor:pointer;width:"+ imgWidth +";height:"+ imgHeight +" \" />";
str=str+"</a>";
}
}
$('#imgFontDiv').append(str);
//thumb.attr('src', res['src']+'?'+timestemp);
//litbox.attr('href', res['src']+'?'+timestemp);
lightbox.refresh();
$('.jpgImgFont').attr('style', 'width: ' + imgWidth + '; height: ' + imgHeight + ";" ).hide().fadeIn('slow');
if(res['img1path']!=""){
img1path.value=res['img1path'];
}
if (imgid == 'imgFont') {
document.getElementById("photoName").value=res['srcStr'].substring(res['srcStr'].lastIndexOf("/")+1);
}
//}
}
});
}
function goClearPhoto(textID,imgID,hrefID,photoName){
var _file = document.getElementById(textID);
if(_file.files)
{
_file.value = "";
}
else
{
if (typeof _file != "object")
{
return null;
}
var textID=document.getElementById(textID);
textID.value="";
var timestemp = new Date().getTime();
var src=document.getElementById("carPermitDefaultPath").value;
var thumb = $('img#'+imgID);
var litbox = $('a#'+hrefID);
thumb.attr('src',"/groupware/images/PdfSample.png");
thumb.attr('style', 'width:230px;height:240px;border:0px;vertical-align:middle;cursor:pointer;' ).hide().fadeIn('slow');
litbox.attr('href',"/groupware/images/PdfSample.png"+'?'+timestemp);
$('.pdfImg').remove();
litbox.show();
lightbox.refresh();
var photoName=document.getElementById(photoName);
photoName.value=null;
var imgFont= document.getElementById(imgFont);
imgFont.value = null;
}
$("#imgFile").val("");
$("#img1path").val("");
}
html:
<body onload="showImage('insUpdPermitPhoto','imgFont','pfont');>
<div style="margin-top:3px;margin-bottom:-8px">
<span class="sl-custom-file" style="">
<input type="text" id="img1path" placeholder="対応フォーマット:pdfのみ" readonly="true" class="input-height" style="width:260px;height:20px;"/>
<button class="btn btn-small" id="reference" type="button" style="margin-left:-2px;margin-top:-12px">
<span style="color:black;">参照</span>
</button>
<input type="file" id='insUpdPermitPhoto' class="fileTransIE10 ui-input-file" name="ufile" onChange="getValue(this,'img1path')" />
</span>
<a href="javascript:void(0)" onfocus="this.blur();" onClick="goClearPhoto('img1path','imgFont','pfont','photoName');" class="btn btn-small" style="margin-top:-15px;">
<span style="color:black;">削除</span>
</a>
</div>
后台用方法把图片复制到指定路径就可以了
‘叁’ 用js、jquery如何实现上传图片的预览
$("#btnLoadPhoto").upload({ url: "../UploadForms/RequestUpload.aspx?action=photo", type: "json", callback: calla });
//获得表单元素
HttpPostedFile oFile = context.Request.Files[0];
//设置上传路径
string strUploadPath = "temp/";
//获取文件名称
string fileName = context.Request.Files[0].FileName;
补充:JQuery是继prototype之后又一个优秀的Javascript库。它是轻量级的js库 ,它兼容CSS3,还兼容各种浏览器(IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+),jQuery2.0及后续版本将不再支持IE6/7/8浏览器。jQuery使用户能更方便地处理HTML(标准通用标记语言下的一个应用)、events、实现动画效果,并且方便地为网站提供AJAX交互。jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。jQuery能够使用户的html页面保持代码和html内容分离,也就是说,不用再在html里面插入一堆js来调用命令了,只需要定义id即可。