在本文中,我们将详细介绍ajaxFileUpload+ThinkPHP+jqGrid图片上传与显示的各个方面,同时,我们也将为您带来关于$.ajaxFileUploadisnotafunction,使
在本文中,我们将详细介绍ajaxFileUpload+ThinkPHP+jqGrid 图片上传与显示的各个方面,同时,我们也将为您带来关于$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、ajaxFileUpload 图片上传工具、ajaxFileUpload+php图片上传预览、ajaxFileUpload上传图片的有用知识。
本文目录一览:- ajaxFileUpload+ThinkPHP+jqGrid 图片上传与显示
- $.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错
- ajaxFileUpload 图片上传工具
- ajaxFileUpload+php图片上传预览
- ajaxFileUpload上传图片
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 + '"/>' }
- 下面为上传用到的 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 + '"'; 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] ); } });
$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错
$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错,这是什么原因?ajaxFileUpload 图片上传工具
----------------------------------------------- 前端 ------------------------------------------
1. 先导入<script type="text/javascript" src="/js/ajaxfileupload.js"></script>
2. jsp页面的上传图片按钮
3. 设置绑定事件 , 将上传的图片显示到前端
4. 相应的css代码
-------------------------------------- 服务端 ---------------------------------------------
1.
// 上传图片到中转目录下
List<SortFile> sortFileArray = ImageUploadUtil.saveFile(request,paramConfig.getTempPath(), "cdn");
2.
/
**
*
* @param request
* @param tempPath (临时存放路径)
* @param fileSaveDirName (保存文件的目录名)
* @return fullFilePath (返回完整的文件路径)
* @throws Exception
*/
public static List<SortFile> saveFile(HttpServletRequest request,String tempPath,String fileSaveDirName) throws Exception {
List<SortFile> sortFileArray = new ArrayList<SortFile>();
String suffix = null;//后缀名
try{
if (!ServletFileUpload.isMultipartContent(request)) {
return null;
}
String fileSavePath = tempPath;
if(tempPath.indexOf("/",tempPath.length() - 1) >= 0) {
fileSavePath += fileSaveDirName;
} else {
fileSavePath += File.separator + fileSaveDirName;
}
diskFileItemFactory factory = new diskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 设置临时文件存储位置
File file = new File(tempPath);
// 设置内存缓冲区,超过后写入临时文件
factory.setSizeThreshold(10240);
// 创建文件夹
if(!file.exists()){
file.mkdirs();
}
factory.setRepository(file);
List<?> items = upload.parseRequest(request);
FileItem item = null;
for (int i = 0 ;i < items.size(); i++){
item = (FileItem) items.get(i);
if (!item.isFormField() && item.getName()!=null && item.getName().length()>0) {
File dir = new File(fileSavePath);
if(!dir.exists()){
dir.mkdirs();
}
suffix = getSuffix(item.getName());
String fullFilePath = fileSavePath+File.separator+DateUtil.ymdFormat(new Date())+UUID.randomUUID().toString()+"."+suffix;
// 保存文件
item.write(new File(fullFilePath));
SortFile sortFileInfo = new SortFile();
sortFileInfo.setFilePath(fullFilePath);
sortFileInfo.setFileName(item.getName());
sortFileInfo.setValue(item.getFieldName());
// 页面配置的上传文件名需要设置为 pic_0,pic_1... e.g. <input type="file" name="pic_0" />
String sortStr = item.getFieldName().replace("pic_","");
sortFileInfo.setSortNum(StringUtil.isEmpty(sortStr) ? 0 : (StringUtil.isNumeric(sortStr) ? Integer.parseInt(sortStr) : 0));
sortFileArray.add(sortFileInfo);
}
}
} catch(Exception e) {
log.error("saveFile 到临时目录报错: fileSaveDirName="+fileSaveDirName,e);
}
sort(sortFileArray);
return sortFileArray;
}
ajaxFileUpload+php图片上传预览
后台是利用SWFUpload上传图片,是flash+js的组合,如果不用chrome,经常会提示flash版本过低用不了,感觉还是很不方便的。
这里总结了一利用js ajax上传的插件列表: 7 JAVASCRIPT AJAX FILE UPLOAD PLUGINS
jQuery插件之ajaxFileUpload 原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。
前台做的时候有一个坑,之前是用的$('element').change()来获取事件,但是onchange事件只会被触发一次,网上有提到解决的办法是live('change'),可惜项目jquery太旧并不支持,也不敢随意升级。所以只能直接在input中加入onchange=“function()”来实现。
这里有关于onchange事件的详细讲解:input的onchange事件实际触发条件与解决方法
一、当input捕获到焦点后,系统储存当前值
二、当input焦点离开后,判断当前值与之前存储的值是否不等,如果为true则触发onchange事件。
##前台代码 浏览器自己的file input比较丑,所以一般都display:none然后下面加一个
function uploadRear() { $.ajaxFileUpload({ url:'{url:/ucenter/ajax_addr_identity_upload}',secureuri:false,fileElementId: 'strPhotoRear1',dataType: 'json',success: function (data) { if(data.error == '200'){ $("#img-r").attr('src','{url:/' + data.data + '}'); $('input[name="card_id_reverse"]').val(data.data); $('#strPhotoRear1').val(); } else { art.dialog({ content: data.data }); } } }); }
##php后台代码 利用了一个IUpload的类,foreach $_FILES,检查扩展名和图片木马,然后再上传。 先要了解PHP预定义变量$_FILES的格式:
Array ( [file1] => Array ( [name] => MyFile.txt (comes from the browser,so treat as tainted) [type] => text/plain (not sure where it gets this from) [tmp_name] => /tmp/php/php1h4j1o [error] => UPLOAD_ERR_OK (= 0) [size] => 123 (the size in bytes) ) [file2] => Array ( [name] => MyFile.jpg [type] => image/jpeg [tmp_name] => /tmp/php/php6hst32 [error] => UPLOAD_ERR_OK [size] => 98174 ) )
这是在input name为file1和file2的情况,如果是写为file[img1],file[img2],则处理为了以下模式(官方文档推荐了diverse_array()的trick):
Array ( [file] => Array ( [name] => Array ( [img1] => MyFile.txt [img2] => MyFile.jpg ) ...
controller中的代码,返回处理后的消息给前台:
public function ajax_addr_identity_upload(){ $file_dir = 'upload/addr_identity/'; $uploader = new IUpload('5120'); //5M $sub_dir = date('Y') . '/' . date('m') . '/'. date('d'); $uploader->setDir(trim($file_dir,'/') . '/' . $sub_dir); $res = $uploader->execute(); //判断文件上传并生成数据 if ((isset($res['picfront']) && $res['picfront'][0]['flag'] == 1) || (isset($res['picback']) && $res['picback'][0]['flag'] == 1)) { $return['error'] = '200'; $return['data'] = empty($res['picfront'][0]['fileSrc']) ? $res['picback'][0]['fileSrc'] : $res['picfront'][0]['fileSrc']; $size = filesize($result['data']) / 1024; $code = new Config('code_config'); $max_size = $code->card_id_max_size; if($size > $max_size){ $proportion = number_format(($max_size/$size)*100); $this->createThumb($return['data'],$proportion); } } else { $return['error'] = '301'; $return['data'] = '上传失败'; } echo json_encode($return);exit(); }
IUpload类中比较关键的方法
public function setDir($path,$chmod=0777){ $dir = is_dir($path) or (self::mkdir(dirname($path),$chmod) and mkdir($path,$chmod)); $dir = strtr($dir,'\\','/'); $this->dir = substr($dir,-1)=='/' ? $dir : $dir.'/'; } public function execute(){ //总的文件上传信息 $info = array(); foreach($_FILES as $fid => $file) { $fileInfo = array(); //不存在上传的文件名 if(!isset($_FILES[$fid]['name']) || $_FILES[$fid]['name'] == '') { continue; } //上传控件为数组格式 file[]格式 if(is_array($_FILES[$fid]['name'])){ $keys = array_keys($_FILES[$fid]['name']); foreach($keys as $key) { //调用成员检查上传类型,pathinfo()获取 $fileInfoArray = pathinfo($_FILES[$fid]['name'][$key]); #code 检查上传大小 $_FILES[$field]['size'][$key] #code 图片木马检测 #开始上传 is_uploaded_file/mkdir/move_upload_file(tmp_name,dir+name) } } else{ //非文件数组上传方式 #$fileInfo[0]['name'] = $_FILES[$field]['name']; } $info[$fid] = $fileInfo; }
ajaxFileUpload上传图片
jsp页面
<div>
<input id="uid" type="hidden">
input type="file" name="file" id="fn" onchange="select_img();">
<img id='target' https://www.jb51.cc/tag/dis/" target="_blank">display:none;" />
引用的js
jquery.ajaxfileupload.js
js代码
$(function () {
$('input[type=text]').validateBox();
});
function uploadP(id){
$("#uid").val(id);
$("#uploadpictrue").dialog("open");
}
function select_img() {
var id=$("#uid").val();
var value = $("#fn").val();
var ext = value.substring(value.lastIndexOf(".") + 1).toLowerCase();
if (ext == null
|| ext == ""
|| (ext != "jpg" && ext != "gif" && ext != "bmp" && ext != "jpeg" && ext != "png")) {
$.messager.alert("操作提示","图片格式错误","info");
} else{
$.ajaxFileUpload({
url : "<%=basePath%>uploadImgFile.html?id="+id,
secureuri : false,// 一般设置为false
fileElementId : 'fn',// 文件上传空间的id属性
dataType : 'text',// 返回值类型 一般设置为json
success : function(data,status) // 服务器成功响应处理函数
{
var path=data.substring(8,data.length-3);
if(path=="fail1"){
$("#fn").val("");
$.messager.alert("操作提示","文件超过4MB,请您重新上传","info");
}else{
$("#target").attr("src",getRootPath() + data);
$("#btnl").css("display","block");
$("#target").css("display","block");
}
},
error : function(data,status,e)// 服务器响应失败处理函数
{
$.messager.alert("操作提示",e,"info");
}
});
}
}
function getRootPath() {
// 获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
var curWwwPath = window.document.location.href;
// 获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
// 获取主机地址,如: http://localhost:8083
var localhostPaht = curWwwPath.substring(0,pos);
// 获取带"/"的项目名,如:/uimcardprj
var projectName = pathName
.substring(0,pathName.substr(1).indexOf('/') + 1);
return (localhostPaht + projectName) + "/";
}
后台代码
@SuppressWarnings("unchecked")
@RequestMapping(value = "/uploadImgFile.html")
public @ResponseBody void uploadImgFile(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("file") multipartfile file,int id)
throws Exception {
JSONObject jsonObject=new JSONObject();
//文件大小
double fileSizeDouble = get2Double(((double) file.getSize() / 1024) / 1024);
String fileSize = fileSizeDouble + "MB";
if (fileSizeDouble > 4.0) {
jsonObject.put("msg","fail1");
// ResponseUtil.write(response,jsonObject);
}else {
String sql="from TabExpert te where te.expertid='"+id+"'";
TabExpert tabExpert=tabExpertSercive.getTabExpertListByHql(sql).get(0);
String msg="";
// 获取当期时间,作为文件名,避免重复
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String fileTime = sdf.format(new Date());
String fileName = file.getoriginalFilename();
System.out.println(fileName);
String type = fileName.substring(fileName.lastIndexOf(".") + 1);
/*if (fileName.length() > 0) {
if (!type.equals("jpg") && !type.equals("bmp")
&& !type.equals("gif") && !type.equals("png")
&& !type.equals("jpeg")) {
jsonObject.put("msg","图片格式错误");
}
}else{
*/
// 上传的文件放在“realPath”目录下
String realPath1 = request.getSession().getServletContext()
.getRealPath("houtai/image/" + fileTime);
if ((new File(realPath1).isDirectory())) {
System.out.println("文件夹已存在!创建失败!");
} else {
new File(realPath1).mkdir();
System.out.println("创建文件夹成功!");
}
if (fileName.length() > 0) {
// 存入照片
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(
realPath1,fileName));
// 相片路径
String realPath = realPath1 + "\\" + fileName;
System.out.println("========================================");
// 将文件名存入数据库
// realPath=realPath+"\\"+fileName;
int beginIndex = realPath.lastIndexOf("houtai");
realPath = realPath.substring(beginIndex,realPath.length());
tabExpert.setExt0(realPath.replace("\\","/"));
tabExpert.setExt1(fileName);
try {
tabExpertSercive.updateTabExpert(tabExpert);
msg=tabExpert.getExt0();
ResponseUtil.write(response,msg);
jsonObject.put("msg",tabExpert.getExt0());
System.out.println(tabExpert.getExt0());
} catch (Exception e) {
// Todo: handle exception
jsonObject.put("msg","上传失败!");
}
}
/*}*/
}
ResponseUtil.write(response,jsonObject);
}
关于ajaxFileUpload+ThinkPHP+jqGrid 图片上传与显示的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于$.ajaxFileUpload is not a function,使用ajaxfileupload.js时提交报错、ajaxFileUpload 图片上传工具、ajaxFileUpload+php图片上传预览、ajaxFileUpload上传图片的相关信息,请在本站寻找。
本文标签: