前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >ajaxFileUpload+ThinkPHP+jqGrid 图片上传与显示

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

作者头像
zcqshine
发布于 2018-05-11 08:25:02
发布于 2018-05-11 08:25:02
2.3K00
代码可运行
举报
文章被收录于专栏:zcqshine's blogzcqshine's blog
运行总次数:0
代码可运行
  • jqgrid上要显示图片和上传图片的列,格式如下:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
{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 此处与图片的上传没关系.
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
function alarmFormatter(cellvalue, options, rowdata){
        return '<img src="__MODULE__/download/download?id= '+ rowdata.icon + '" style="width:50x;height:50px" />'
    }
  • 下面为上传用到的 js 文件 upload.js
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 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上传代码部分
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e)
                {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, 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, xml, null, 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, xml, null, 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, xml, status, e ) {
        // If a local callback was specified, fire it
        if ( s.error )
            s.error( xml, status, e );

        // Fire the global callback
        if ( s.global )
            jQuery.event.trigger( "ajaxError", [xml, s, e] );
    }
});
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
ajaxFileUpload文件
从网上下了个ajaxfileupload的文件,结果不支持ie,又出现各种问题,上网查了,修改了可以支持各种浏览器。
Dylan Liu
2019/07/01
6490
spring boot +ajax上传文件前后端分离完整实现示例代码
首先页面初始化先给隐藏input 类型为file的上传按钮绑定事件,并且增加上传按钮的change事件函数。
跟着飞哥学编程
2022/11/30
8420
spring boot +ajax上传文件前后端分离完整实现示例代码
thinkphp ajaxfileupload实现异步上传图片的示例
thinkphp开发图片上传,图片异步上传是目前比较方便的功能,这里我就不写css文件了,将代码写出来。引入核心文件下载https://github.com/carlcarl/A...
用户2323866
2021/07/02
1K0
Ajax简单实现文件异步上传的多种方法
void append(DOMString name, DOMString value)
潇洒哥和黑大帅
2019/02/25
1.7K0
asp.net mvc 实现上传文件带进度条
思路:ajax异步上传文件,且开始上传文件的时候启动轮询来实时获取文件上传进度。保存进度我采用的是memcached缓存,因为项目其他地方也用了的,所以就直接用这个啦。注意:不能使用session来保
晓晨
2018/06/22
4K1
php+ajax实现无刷新文件上传功能(ajaxuploadfile)
本文实例为大家分享了php+ajax实现无刷新文件上传的具体代码,供大家参考,具体内容如下
用户8675788
2021/07/13
1.8K0
利用ajaxFileUpload.js实现多文件异步上传功能
  AjaxFileUpload.js是网络开发者写好的插件放出来供大家使用用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。在这里我将网络上下载下来的插件包进行了修改,以实现多文件上传功能,下面我给大家讲解一下该插件的用法 。   改写后的插件源码(使用的时候将插件源码拷贝到您新建的js文件中保存,然后对js文件进行引用): jQuery.extend({     handleError: function (s, xhr, status, e) {         // If a 
Sindsun
2018/04/28
2.6K0
利用ajaxFileUpload.js实现多文件异步上传功能
ajaxfileupload 实现多文件上传
官网下载ajaxfileupload.js: 修改源码: jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" s
大道七哥
2019/09/10
1.7K0
thinkphp3.2处理多张图片上传
在做后台图片编辑和上传的时候往往会遇到比较棘手的问题,就是如何上传多张图片,本来以为要在input后面加个按钮,判断要添加的时候,在创一个input,这样子的话每个图片都有自己一个对应的name,这样后台便会拿到图片的路径。
IT工作者
2022/02/24
1.2K0
jQuery+ajax实现简单的上传图片功能
在前面的文章里面有写到,用vue上传图片的功能,vue-element-admin上传图片的功能:https://www.jianshu.com/p/383e1f2f4276,那如果是在jQuery里面,图片上传要怎么写?今天记录一个jQuery+ajax实现简单的上传图片功能。
王小婷
2020/10/29
6.1K1
jQuery+ajax实现简单的上传图片功能
SpringMVC--文件下载
接着上篇SpringMVC--文件上传,只是实现了文件的上传,接着来实现文件的下载
aruba
2022/05/25
2180
SpringMVC--文件下载
前端开发---异步上传文件
有一个名为ajaxFileUpload的JQuery插件可以利用iframe来实现前端页面中异步上传文件。
MiaoGIS
2020/11/25
1.5K0
前端开发---异步上传文件
ThinkPHP上传文件
<form id="upload" method='post' action="__URL__/upload/" enctype="multipart/form-data">
PM吃瓜
2019/08/13
2.5K0
HTML5上传图片,后台使用java
<script src="${base_path}/view/html/js/flexible.js"></script> <script src="${base_path}/view/html/lib/jquery.js"></script> <script src="${base_path}/view/html/lib/mobileBUGFix.mini.js"></script> <script src="${base_path}/view/html/lib/fastclick/fastclick.js"></script> <script src="${base_path}/view/html/lib/exif.js"></script> <script src="${base_path}/view/html/lib/jquery.base64.min.js"></script> <script src="${base_path}/view/html/js/common.js"></script> <script src="${base_path}/view/html/js/membercenter/certification.js"></script>
用户5640963
2019/07/26
3.3K0
微信小程序开发(二)图片上传+服务端接收
这里的filePath就是图片的存储路径,类型居然是个String,也就是 只能每次传一张图片,我以前的接口都是接收一个array,我本人又是一个半吊子的php,只能自己去改接收图片的接口。
开发者技术前线
2020/11/23
2.1K0
微信小程序开发(二)图片上传+服务端接收
.net mvc + layui做图片上传(一)
  图片上传和展示是互联网应用中比较常见的一个功能,最近做的一个门户网站项目就有多个需要上传图片的功能模块。关于这部分内容,本来功能不复杂,但后面做起来却还是出现了一些波折。因为缺乏经验,对几种图片上传的方法以及使用范围和优缺点都不太了解,导致在做相关功能时也确实走了一些弯路。
CherishTheYouth
2019/07/30
1.5K0
.net mvc + layui做图片上传(一)
SSM 项目 ——— 小米商城后台管理系统
本项目主要目的是使学员更深层的了解IT企业的文化和岗位需求、模拟企业的工作场景,分享研制成果,增加学员对今后工作岗位及计算机应用开发对客观世界影响的感性认识,使学员对技术有更深入的理解,在今后工作中能有更明确的目标和方向。并能为日后职业规划提供很好的指导作用。
全栈程序员站长
2022/09/14
3.6K0
SSM 项目 ——— 小米商城后台管理系统
JAVA中如何图片异步上传
来源:程序员头条:http://www.90159.com/2015/12/15/java-upload-picture/ 在java中要实现异步上传要提前做好准备,对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件。 这个common-fileupload上传组件的jar包可以去apache官网上面下载,也可以在st
编程范 源代码公司
2018/04/16
2.4K0
ajaxfileupload上传文件和报错syntaxerror: Unexpected end of input(…)
jQuery插件AjaxFileUpload可以实现ajax文件上传,下载地址:http://www.phpletter.com/contents/ajaxfileupload/ajaxfileupload.js
仙士可
2019/12/19
2K0
ajaxfileupload上传文件和报错syntaxerror: Unexpected end of input(…)
JQuery文件上传插件ajaxFileUpload在Asp.net MVC中的使用
0 ajaxFileUpload简介 ajaxFileUpload插件是一个非常简单的基于Jquery的异步上传文件的插件,使用过程中发现很多与这个同名的,基于原始版本基础之上修改过的插件,文件版本比较多,我把我自己使用的ajaxFileUpload文件上传到博客园上了,想要使用的朋友可以下载:http://files.cnblogs.com/files/fonour/ajaxfileupload.js。 整个插件源码不到200行,实现非常简单,大致原理就是通过js动态创建隐藏的表单,然后进行提交操作,达到
阿炬
2018/05/11
3.3K0
相关推荐
ajaxFileUpload文件
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文