ajaxFileUpload+ThinkPHP+jqGrid 图片上传与显示

  • jqgrid上要显示图片和上传图片的列,格式如下:
{label:'图片',name:'icon',index:'icon',autowidth:true,formatter:alarmFormatter,editable:true,edittype:'custom',editoptions:{custom_element: ImgUpload,custom_value:GetImgValue}},

注意:edittype要为custom 也就是自定义编辑格式.

editoptions:{custom_element: ImgUpload,custom_value:GetImgValue}}

  • jqgrid 的列表里显示图片用到的 js function 此处与图片的上传没关系.
function alarmFormatter(cellvalue,options,rowdata){
        return '<img src="__MODULE__/download/download?id= '+ rowdata.icon + '" style="width:50x;height:50px" />'
    }
  • 下面为上传用到的 js 文件 upload.js
/**
 4. 自定义文件上传列
 5. @param value
 6. @param editOptions
 7. @returns {*|jQuery|HTMLElement}
 8. @constructor
 */
function ImgUpload(value,editOptions) {
    var span = $("<span>");
    var hiddenValue = $("<input>",{type:"hidden",val:value,name:"fileName",id:"fileName"});
    var image = $("<img>",{name:"uploadImage",id:"uploadImage",value:'',style:"display:none;width:80px;height:80px"});
    var el = document.createElement("input");
    el.type = "file";
    el.id = "imgFile";
    el.name = "imgFile";
    el.onchange = UploadFile;
    span.append(el).append(hiddenValue).append(image);
    return span;
}
/**
 9. 调用 ajaxFileUpload 上传文件
 10. @returns {boolean}
 11. @constructor
 */
function UploadFile() {
    $.ajaxFileUpload({
        url : 'index.php/Home/upload/upload',type : 'POST',secureuri:false,fileElementId: 'imgFile',dataType : 'json',success: function(data,status){
            //显示图片
            $("#fileName").val(data.id);
            $("#uploadImage").attr("src","index.php/Home/download/download?id=" + data.id);
            $("#uploadImage").show();
            $("#imgFile").hide()
        },error: function(data,status,e){
            alert(e);
        }
    });
    return false;
}
/**
 12. icon 编辑的时候该列对应的实际值
 13. @param elem
 14. @param sg
 15. @param value
 16. @returns {*|jQuery}
 17. @constructor
 */
function GetImgValue(elem,sg,value){
    return $(elem).find("#fileName").val();
}
  • 下面为ThinkPHP上传代码部分
<?php
/**
 * 上传文件
 * Created by PhpStorm.
 * User: zcqshine
 * Date: 15/12/31
 * Time: 14:16
 */

namespace Home\Controller;
use Home\Common\HomeController;
use Think\Upload;

class UploadController extends HomeController
{
    public function upload(){
        $upload = new Upload();
        $upload->maxSize = 4194304; //4MB
        $upload->exts = array('jpg','gif','png','jpeg');
        $upload->rootPath = C("FILE_PATH"); //根目录
        $upload->autoSub = false;
//        $upload->savePath = C("FILE_PATH"); //附件上传目录,相对于根目录
//        $upload->saveName = array('uniqid','');

        //上传文件
        $info = $upload->uploadOne($_FILES['imgFile']);
        if(!$info){ //上传错误提示信息
            $this->e($upload->getError());
            $this->returnError($upload->getError());
        }else{
            //存数据库部分
            $photo = D('photo');
            $photo->name = $info['savename'];
            $photo->realName = $info['name'];
            $photo->suffix = $info['ext'];
            $photo->size = $info['size'];
            //...省略部分代码
            $id = $photo->add();
//            $this->ajaxReturn(array('msg'=>$id),"JSON");
            echo json_encode(array('id'=>$id));
        }
    }
}

因为 thinkphp 自带的 ajaxReturn 返回的数据带有pre标签,会导致ajaxFIleUpload 解析不了,所以用了原生的 echo json_encode() 函数

  • ajaxFileUpload.js
jQuery.extend({
    createUploadIframe: function(id,uri)
    {
        //create frame
        var frameId = 'jUploadFrame' + id;
        var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
        if(window.ActiveXObject)
        {
            if(typeof uri== 'boolean'){
                iframeHtml += ' src="' + 'javascript:false' + '"';

            }
            else if(typeof uri== 'string'){
                iframeHtml += ' src="' + uri + '"';

            }
        }
        iframeHtml += ' />';
        jQuery(iframeHtml).appendTo(document.body);

        return jQuery('#' + frameId).get(0);
    },createUploadForm: function(id,fileElementId,data,fileElement)
    {
        //create form
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        if(data)
        {
            for(var i in data)
            {
                jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
            }
        }
        var oldElement;
        if(fileElement == null)
            oldElement = jQuery('#' + fileElementId);
        else
            oldElement = fileElement;

        var newElement = jQuery(oldElement).clone();
        jQuery(oldElement).attr('id',fileId);
        jQuery(oldElement).before(newElement);
        jQuery(oldElement).appendTo(form);

        //set attributes
        jQuery(form).css('position','absolute');
        jQuery(form).css('top','-1200px');
        jQuery(form).css('left','-1200px');
        jQuery(form).appendTo('body');
        return form;
    },ajaxFileUpload: function(s) {
        // TODO introduce global settings,allowing the client to modify them for all requests,not only timeout		
        s = jQuery.extend({},jQuery.ajaxSettings,s);
        var id = new Date().getTime()
        var form = jQuery.createUploadForm(id,s.fileElementId,(typeof(s.data)=='undefined'?false:s.data),s.fileElement);
        var io = jQuery.createUploadIframe(id,s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
        {
            jQuery.event.trigger( "ajaxStart" );
        }
        var requestDone = false;
        // Create the request object
        var xml = {}
        if ( s.global )
            jQuery.event.trigger("ajaxSend",[xml,s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
        {
            var io = document.getElementById(frameId);

            try
            {
                if(io.contentWindow)
                {
                    xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                    xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

                }else if(io.contentDocument)
                {
                    xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }
            }catch(e)
            {
                jQuery.handleError(s,xml,null,e);
            }
            if ( xml || isTimeout == "timeout")
            {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
                    {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml,s.dataType );
                        // If a local callback was specified,fire it and pass it the data
                        if ( s.success ){
                            s.success( data,status );
                        }
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess",s] );
                    } else
                        jQuery.handleError(s,status);
                } catch(e)
                {
                    status = "error";
                    jQuery.handleError(s,e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete",s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml,status);

                jQuery(io).unbind()

                setTimeout(function()
                {	try
                {
                    jQuery(io).remove();
                    jQuery(form).remove();

                } catch(e)
                {
                    jQuery.handleError(s,e);
                }

                },100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 )
        {
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            },s.timeout);
        }
        try
        {

            var form = jQuery('#' + formId);
            jQuery(form).attr('action',s.url);
            jQuery(form).attr('method','POST');
            jQuery(form).attr('target',frameId);
            if(form.encoding)
            {
                jQuery(form).attr('encoding','multipart/form-data');
            }
            else
            {
                jQuery(form).attr('enctype','multipart/form-data');
            }
            jQuery(form).submit();

        } catch(e)
        {
            jQuery.handleError(s,e);
        }

        jQuery('#' + frameId).load(uploadCallback);
        return {abort: function(){
            try
            {
                jQuery('#' + frameId).remove();
                jQuery(form).remove();
            }
            catch(e){}
        }};
    },uploadHttpData: function( r,type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;

        // If the type is "script",eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object,if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    },handleError: function( s,e ) {
        // If a local callback was specified,fire it
        if ( s.error )
            s.error( xml,e );

        // Fire the global callback
        if ( s.global )
            jQuery.event.trigger( "ajaxError",s,e] );
    }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方法的时候参数processData默认为true(该方法为jQuery独有的) 默认情况下会将发送的数据序列化以适应默认的内容类型application/x-www-form-urlencoded 如果想发送不
form表单提交的几种方式 表单提交方式一:直接利用form表单提交 html页面代码: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;title&gt;Ins
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于注册名称的检测能即时显示。常见的用户注册是用户输入用户名,后台程序检测数据库中用户名是否重复而做出注册的成功与失败之提示(当用户注册重名时将返回重新注册),或者稍微人性化一点就是在用户名文本框后添加一个检测按钮,让用户检测后再做注册。以上操作,对于用户体验方面来说是比较“差劲”的,一个很好的用户体验就是:当用户输入完注册用户名后,Web系统应能即时检查并即时_用户注册 实时异步检测
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在客户端和服务器之间创建复杂的JSON数据传输层。一、 引言毫无疑问,AJAX已经成为当今Web开发中一种强有力的用户交互技术,但是它的许多可能性应用仍然鲜为人知。在本文中,我们将来共同探讨如何 使用JavaScript对象标志(JSON)和JSON分析器在服务器和客户端AJAX引擎之间创建复杂而强有力的JSON数据传输层。我们将_ajax技术可行性
文章浏览阅读2.2k次。/************************** 创建XMLHttpRequest对象 **************************/function CreateRequest(){ var xmlObj = null; try { xmlObj = new XMLHttpRequest(); } catch(e) {
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送多个请求,如果只有一个XMLHttpRequest对象,前面的请求还未完成,后面的就会把前面的覆盖 掉,如果每次都创建一个新的XMLHttpRequest对象,也会造成浪费。解决的办法就是创建一个XMLHttpRequset的对象池,如果池里有 空闲的对象,则使用此对象,否则将创建一个新的对象。下面是我最近写的一个简单的类:* XMLHttpReques_xmlhttprequest发送多个请求
文章浏览阅读3.1k次。Ajax 同一页面如何同时执行多个 XMLHTTP 呢,比如博客页,需要同时利用 Ajax 读取作者信息、文章信息、评论信息……我们的第一反应可能是创建多个全局 XMLHTTP 对象,但这并不现实。其实实现方式非常简单,就是给 onreadystatechange 对应的回调函数加上参数,以下代码是解决方案中一个函数中的一段代码。xmlhttp.open("GET", "ajax_proc_ajax响应多个mxl文件
文章浏览阅读1.5k次。数据岛指的是存在Html网页中的xml代码段,它在Html中形成了一个数据的集合,数据岛允许我们在Html网页中集成xml,对xml编写脚本.数据岛有它特有的形式,由标记xml开始,在开始标记中要有一个ID属性,用于指定该指定数据岛的名称。 (当然要以/xml结束).元素xml包含的内容就是xml代码。数据岛也分为2种:1)内嵌的数据岛形式2)外嵌的数据岛形式说了那么多废话,还_数据中岛计算模式
文章浏览阅读2.1k次。AJAX 流行之后,总想好好学习一下。但是众多的框架实在难以选择。说明一下 ASP.NET AJAX 并不包括在 AJAX 框架之中。刚开始学了 JQuqery, 众多的 $get(),...等等符号早已把我搞晕了。暂时就放弃了。后来学习 ASP.NET AJAX ,在微软的领导下,逐渐由服务器端转向客户端编程。 激起我客户端编程的兴趣,才想起学习一下了 Jquery. 随着WEB2._jquery ajax asp.net 认证
文章浏览阅读1.7k次。前段时间在用google map api的函数库的时候,发现里面的downloadUrl函数非常好用,所以自己写了一个。用腻了那些什么框架什么池,到头来发现越简单的东西越是适合我这种懒人。downloadUrl(url, callback, data);参数说明: url不用说了; callback是回调函数,函数调用的时候会有两个参数:data, responseCode,data就_xmlhttprequest downloadurl
文章浏览阅读956次。前些时间写了几篇关于XMLHTTP运用的实例.(可以到http://dev.csdn.net/user/wanghr100看之前的几编关于XMLHTTP的介绍.)近来看论坛上经常有人提问关于如何无刷新,自动更新数据.传统上,我们浏览网页,如果加入最新的数据.只能是等我们重新向服务器端请求时才能显示出来.但是,对于一些时效性很强的网站.传统的这种做法是不能满足的.我们可以让程序自动刷新.定时_后端xml怎么实现数据有救新增,没有就更新
文章浏览阅读3.3k次。 XMLHttpRequest调用XMLHttpRequest Call ●●●调用,回调,下载,抓取,实时,查询,远程通信(Remoting),远程通信脚本(RemoteScripting),同步,上传,XMLHttpRequest图6-2:XMLHttpRequest调用 目标故事Reta正在一个批发商网站上购买商品。每次她添加一个商品到购物车时,web站点发出_createxmlhttpre
文章浏览阅读1.3k次。function clearitem(){ var drp1 = document.getElementById("drp1"); while(drp1.options.length>0) { drp1.options.remove(0); } }//动态更改方法(根据城市代码取得该市商业区并添加到DropDownList中_dropdownlist根據動態變化
文章浏览阅读1.9k次。因為 Json.net 是有附原始碼的,他也附了單元測試的專案,底下是我額外增加的UnitTest,我的目標就是讓底下的測試可以pass,而且原來的Test 也要都能通過。 ValueTypeTest.csusing System;using NUnit.Framework;namespace Newtonsoft.Json.Test { [TestFixture] public cl_vb 無效的 json 基本型別
文章浏览阅读844次。利用XMLHTTP无刷新获取数据. 客户端和服务器端数据的交互有几种方法.1.提交,通过提交到服务器端.也称"有刷新"吧.2.通过XMLHTTP无刷新提交到服务器端,并返回数据.也称"无刷新"吧.利用XMLHTTP我们可以实现很多很强大的应用.这文章主要介绍它的一些简单的应用.附:因为XMLHTTP是IE5.0+支持的对象.所以你必须要有IE5.0+才能看到效果.client.htm_xmlhttp取源码没有更新
文章浏览阅读1.8k次。Json.Net 無法序列基本型別(string, int),Asp.Net Ajax 無法正確序列日期,AjaxPro序列出我不想要的_type字串 1. Json.Net 是我最常使用的序列/反序列json套件,標榜速度快,對於一對多關係的object 也都能正常運作, 己能滿足我平日的需要,但前幾天突然有個情況,我要序列的是一個泛型參數,該參數不一定是物object型別,有可能是st_token string in state start
文章浏览阅读1.3k次。转载自:http://www.cnblogs.com/JeffreyZhao/archive/2007/01/31/update_the_updatepanels_by_js.html众 所周知,UpdatePanel是通过Trigger来更新的。被设定为Trigger的控件在PostBack之后会被客户端所截获,并且使用 XMLHttpRequest对象发送内容,然后服务器端由ScriptMan_web.ui.updatepanel 和 updatepanel 的区别
文章浏览阅读1.9k次。有些时候,只是需要更新页面的一个部分甚至只是更新中间的几个数据却需要从服务器DOWN整个页面,导致各种资源的浪费。使用数据岛技术可以很好的解决这个问题:通过定时器或用户事件触发数据岛(XML对象)象服务器获取数据,在数据获取完成后,适时更新相关数据。示例HTML部分:http://localhost/WebService/LoadData/FeaturedService.asmx/GetScore_web数据岛
文章浏览阅读1k次。在页面上使用ActiveXObject的代价是很大的,如果我们的无刷新页面使用xmlhttp技术,我们或许需要频繁的建立xmlhttp对象,当然 我们也可以使用全局变量来cache一个xmlhttp对象实例。但是这样的方法适合于同步方式xmlhttp通信,而对于异步方式xmlhttp通信将 会出现问题。由于没有了进程的堵塞,用户可能再次调用同一个xmlhttp实例,如果这时前一个通信未完成,那么就
文章浏览阅读998次。 by Lokesh Dhakar 译: croc查看原文概要:Lightbox JS 是一个简单而又谦恭的用来把图片覆盖在当前页面上的脚本. 它能被快速安装并且运作于所有流行的浏览器.最新更新 Version 2.0 图片集: 分组相关的图片并且能轻松的导航它们 视觉特效: 奇特的自适应调整 向后兼容: yes! 点击这里查看实例_on lightbox 2 by lokesh dhakar