html代码:
<div id="fileQueue"></div> <--进度展示--><div id="uploadify" class="attch-img-btn"> </div><--上传按钮-->
js代码
$(function(){var houseId = '';$("#uploadify").uploadify({debug : false,swf : '/gsym/resource/js/uploadify/uploadify.swf', //swf文件路径method : 'get', // 提交方式uploader : '/gsym/file/fileload', // 服务器端处理该上传请求的程序(servlet, struts2-Action)preventCaching : true, // 加随机数到URL后,防止缓存buttonCursor : 'hand', // 上传按钮Hover时的鼠标形状//buttonImage: '/gsym/resource/images/atimg-up-bgad.png', // 按钮的背景图片,会覆盖文字buttonText : '', //按钮上显示的文字,默认”SELECTFILES”height : 40, // 单位 pxwidth : 60, // 单位 pxfileObjName : 'filedata', //文件对象名称, 即属性名fileSizeLimit : 1000, // 文件大小限制, 1MfileTypeDesc : 'any', //文件类型说明 any(*.*)fileTypeExts : '*.*;*.txt', // 允许的文件类型,分号分隔formData : {'houseId' : houseId,'path' : path}, //指定上传文件附带的其他数据。也动态设置。可通过getParameter()获取multi : true, // 多文件上传progressData : 'percentage', // 进度显示, speed-上传速度,percentage-百分比 queueID : 'fileQueue', //上传队列的DOM元素的ID号queueSizeLimit : 99, // 队列长度removeCompleted : true, // 上传完成后是否删除队列中的对应元素removeTimeout : 2, //上传完成后多少秒后删除队列中的进度条, requeueErrors : true, // 上传失败后重新加入队列uploadLimit : 20, // 最多上传文件数量successTimeout : 30, //表示文件上传完成后等待服务器响应的时间。超过该时间,那么将认为上传成功。// 在文件被移除出队列时触发 //onCancel : function(file) { alert( 'The file ' + file.name + ' was cancelled!' ); },// 在调用cancel方法且传入参数’*’时触发//onClearQueue : function (queueItemCount) { alert( queueItemCount + ' files were removed from the queue!' ); },// 打开文件对话框 关闭时触发onDialogClose : function(queueData) {/*alert("选中文件数 :" + queueData.filesSelected + "---"+ "加入队列文件:" + queueData.filesQueued + "---"+ "被替换文件 :" + queueData.filesReplaced+ "---" + "取消掉的文件数:"+ queueData.filesCancelled + "---"+ "上传出错的文件数:" + queueData.filesErrored);*/},// 选择文件对话框打开时触发onDialogOpen : function() {/*alert( 'please select files' ) */},// 没有兼容的FLASH时触发onFallback : function() {alert('没有兼容的FLASH!')},// 每次初始化一个队列时触发, 即浏览文件后, 加入一个队列//onInit : function (instance) { alert( 'The queue ID is ' + instance.settings.queueID ) },// 上传文件处理完成后触发(每一个文件都触发一次), 无论成功失败//onUploadComplete : function(file){ alert( 'The file ' + file.name + ' uploaded finished!' ) },// 上传文件失败触发onUploadError : function(file, errorCode, errorMsg,errorString) {alert(file.name + ' 上传失败! ' + '错误代码: ' + errorCode + '错误信息:'+ errorMsg + '错误语句:' + errorString,{icon:6});},// 在每一个文件上传成功后触发onUploadSuccess : function(file, data, response) {alert(file.name + ' 上传成功! ' + '文件大小:' + file.size / 1000 + "kb",{icon:6});getFile_photo();}});
后台
/*** 添加文件* @param session* @param request* @param response*/@RequestMapping("/upload")@ResponseBodypublic void saveFiles(final HttpSession session,@RequestParam(value = "fileCode", required = false) String fileCode,HttpServletRequest request, HttpServletResponse response) {//String fileStringParameter("id");//System.out.println(fileCode+"+++++++++++++++++++++++");// 工厂,DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();// 获取上传文件存放的 目录 , 无则创建String path = Session().getServletContext().getRealPath("res" + File.separator + "uploadFile");//System.out.println("path : " + path);new java.io.File(path).mkdir();/*** 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem* 格式的 然后再将其真正写到 对应目录的硬盘上*/diskFileItemFactory.setRepository(new File(path));// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室diskFileItemFactory.setSizeThreshold(1024 * 1024);ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);//System.out.println(upload);try {// 可上传多个文件@SuppressWarnings("unchecked")List<FileItem> list = (List<FileItem>) upload.parseRequest(request);System.out.println(list);for (FileItem item : list) {// 获取 提交表单的 属性名String name = FieldName();// 字符串类 属性if (item.isFormField()) {String value = String();System.out.println(name + "=" + value);}// 二进制类else {// 获取上传文件的名字String value = Name(); // 1,获取路径int start = value.lastIndexOf("\");// 2,索引到最后一个反斜杠String filename = value.substring(start + 1);// 3,// 截取(+1是去掉反斜杠)String nameOfLast=null;System.out.println(name + "=" + value);File file = null;do {// 生成文件名start = filename.lastIndexOf("."); // 索引到最后一个点nameOfLast=filename.substring(start);filename = filename.substring(0, start) // 不含扩展名的文件+ UUID.randomUUID().toString() // 随机数+ nameOfLast; // 扩展名file = new File(path, filename);} while (ists());// 写到磁盘上去item.write(file);//BasFileRelation basFileRelation=new BasFileRelation();FileRelation fileRelation=new FileRelation();SimpleDateFormat simpleDateFormat;simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");Date date = new Date();String str = simpleDateFormat.format(date);Random random = new Random();int rannum = (int) (Double() * (999999999 - 100000000 + 1)) + 100000000;// 获取9位随机数String number=str+rannum;fileRelation.setFileName(filename);//文件名fileRelation.setFileCode(fileCode);//文件编号,时间精确到毫秒,外加9位随机数String fileType=filename.substring(start);fileRelation.setFileType(nameOfLast);//文件后缀//System.out.println(">>>>>>>>>>>>>>"+nameOfLast);fileRelation.Size()+"KB");//文件大小SysUserSession createUser=(SysUserSession) Session().getAttribute("sysUserSession");String createUserNameUserName();fileRelation.setCreateUser(createUserName);//创建人//文件转成byte[]InputStream ips=null;byte[] b=null;try {ips=new FileInputStream(file);//System.out.println("目前可读取文件有效长度为:"+ips.available());b=new byte[ips.available()];ad(b);//System.out.println("读取后有效长度为:"+ips.available());//System.out.print("数组的内容为:"+b);}catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {if (ips!=null) {ips.close();}} catch (IOException e) {e.printStackTrace();}}fileRelation.setFileIo(b);fileRelation.CurrentTime());//当前时间fileRelationService.addFileRelation(fileRelation);//保存文件及文件信息System.out.println("the upload file's size:" + Size());//FileRelation fileRelation2=fileRelationService.fildAllFile(fileRelation);//System.out.FileName());//System.out.println("文件为"FileIo()+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");}}} catch (Exception e) {e.printStackTrace();}}
/*** 文件读取(服务器方式)* @param request* @param fileCode* @return* @throws FileNotFoundException*/@RequestMapping("/getAllFileList")@ResponseBodypublic String getAllFile(HttpServletRequest request,@RequestParam(value = "fileCode", required = false) String fileCode) throws FileNotFoundException{List<FileRelation> list=fileRelationService.fildAllFile(fileCode);for (FileRelation fileRelation : list) {//System.out.println("文件为》》》》》》》》》》》》》》》》"FileName());//存储路径String filePath = Session().getServletContext().getRealPath("res" + File.separator + "uploadFileDown/"FileName());File path = new Session().getServletContext().getRealPath("res" + File.separator + "uploadFileDown"));//System.out.println("图片路径"+path);OutputStream ops=null;if (!ists()) {path.mkdirs();//如果没有则创建}ops=new FileOutputStream(filePath);try {ops.FileIo());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if (ops!=null) {try {ops.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}System.out.println(list);JSONString(list);}
$.ajax( {type : "get",url : "/gmwp/wsouce/getAllFileList?fileCode="+ opr,dataType : 'json',success : function(result) {$(".imgsrc").empty();for ( var i = 0; i < result.length; i++) {if (result[i].fileType == ".jpg" ) {var src = "<img src=/gmwp/res/uploadFileDown/"+ result[i].fileName + "/>"}}})
FileUpload 插件在相应官网下载
本文发布于:2024-01-30 04:55:18,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170656172019369.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |