『壹』 當點擊帶+的圖片時,彈出手機相冊,可以選擇手機相冊內的圖片上傳,代碼如何寫怎麼實現
首先需要引用 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即可。

