zoukankan      html  css  js  c++  java
  • JAVA图片批量上传JS-带预览功能

    这篇文章就简单的介绍一个很好用的文件上传工具,批量带预览功能。直接贴代码吧,都有注释,很好理解。

    HTML页面

    <!DOCTYPE html>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
    <c:set var="BASE" value="${pageContext.request.contextPath}"/>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>新增照片</title>
    <script type="text/javascript">
    var BASE = "${BASE}";
    </script>
    <!-- 引用控制层插件样式 -->
    <link rel="stylesheet" href="${BASE}/www/css/upload/zyupload-1.0.0.min.css " type="text/css">
    <script type="text/javascript" src="${BASE}/www/js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="${BASE}/www/js/upload/zyupload-1.0.0.min.js"></script>
    </head>
    <body>
    <input type="hidden" id="boxId" value="${boxId}"/>
    	    <div id="zyupload" class="zyupload"></div>  
    	    
    	    
    	    <script type="text/javascript">
    			$(function(){
    				var boxId = $("#boxId").val();
    				// 初始化插件
    				$("#zyupload").zyUpload({
    					width            :   "650px",                 // 宽度
    					height           :   "400px",                 // 宽度
    					itemWidth        :   "140px",                 // 文件项的宽度
    					itemHeight       :   "115px",                 // 文件项的高度
    					url              :   BASE+"/photo/add/"+boxId,  // 上传文件的路径
    					fileType         :   ["jpg","png","txt","js","exe","gif"],// 上传文件的类型
    					fileSize         :   51200000,                // 上传文件的大小
    					multiple         :   true,                    // 是否可以多个文件上传
    					dragDrop         :   true,                    // 是否可以拖动上传文件
    					tailor           :   true,                    // 是否可以裁剪图片
    					del              :   true,                    // 是否可以删除文件
    					finishDel        :   false,  				  // 是否在上传文件完成后删除预览
    					/* 外部获得的回调接口 */
    					onSelect: function(selectFiles, allFiles){    // 选择文件的回调方法  selectFile:当前选中的文件  allFiles:还没上传的全部文件
    						console.info("当前选择了以下文件:");
    						console.info(selectFiles);
    					},
    					onDelete: function(file, files){              // 删除一个文件的回调方法 file:当前删除的文件  files:删除之后的文件
    						console.info("当前删除了此文件:");
    						console.info(file.name);
    					},
    					onSuccess: function(file, response){          // 文件上传成功的回调方法
    						console.info("此文件上传成功:");
    						console.info(file.name);
    						console.info("此文件上传到服务器地址:");
    						console.info(response);
    						$("#uploadInf").append("<p>上传成功,文件地址是:" + response + "</p>");
    					},
    					onFailure: function(file, response){          // 文件上传失败的回调方法
    						console.info("此文件上传失败:");
    						console.info(file.name);
    					},
    					onComplete: function(response){           	  // 上传完成的回调方法
    						console.info("文件上传完成");
    						console.info(response);
    					}
    				});
    				
    			});
    		
    		</script> 
    	</body>
          </body>     
    </html>
    

     JS和CSS、IMAGES文件下载地址https://page69.ctfile.com/fs/3775069-203728262,自己根据html中的导入,找不到的在eclipse全局搜索

      action代码:根据需求改地址

    @RequestMapping(value="/add/{boxId}", method={RequestMethod.POST})
        public void addPhotospost(@PathVariable(value="boxId") String boxId, HttpServletRequest request,HttpServletResponse response ) throws IOException {
            ServletContext servletContext=request.getSession().getServletContext(); 
            String newFileName=""; 
                PrintWriter out = response.getWriter();  
                  
                //文件保存目录路径  
                String savePath = "E:/";  
                //String savePath = this.getServletContext().getRealPath("/") + configPath;  
                  
                // 临时文件目录   
                String tempPath = servletContext.getRealPath("/") + Constant.dirTemp;  
                  
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");  
                String ymd = sdf.format(new Date());  
                savePath += "/" + ymd + "/";  
                //创建文件夹  
                File dirFile = new File(savePath);  
                if (!dirFile.exists()) {  
                    dirFile.mkdirs();  
                }  
                  
                tempPath += "/" + ymd + "/";  
                //创建临时文件夹  
                File dirTempFile = new File(tempPath);  
                if (!dirTempFile.exists()) {  
                    dirTempFile.mkdirs();  
                }  
                  
                DiskFileItemFactory  factory = new DiskFileItemFactory();  
                factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时,将产生临时文件并存储于临时目录中。     
                factory.setRepository(new File(tempPath)); //设定存储临时文件的目录。     
                ServletFileUpload upload = new ServletFileUpload(factory);  
                upload.setHeaderEncoding("UTF-8");  
                try {  
                    List items = upload.parseRequest(request);  
                    System.out.println("items = " + items);  
                    Iterator itr = items.iterator();  
                      
                    while (itr.hasNext())   
                    {  
                        FileItem item = (FileItem) itr.next();  
                        String fileName = item.getName();  
                        long fileSize = item.getSize();  
                        if (!item.isFormField()) {  
                            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
                            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
                             newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
                            try{  
                                File uploadedFile = new File(savePath, newFileName);  
                                
                                OutputStream os = new FileOutputStream(uploadedFile);  
                                InputStream is = item.getInputStream();  
                                byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度  
                                int length = 0;    
                                while( (length = is.read(buf)) > 0 ){    
                                    os.write(buf, 0, length);    
                                }    
                                //关闭流    
                                os.flush();  
                                os.close();    
                                is.close();    
                                System.out.println("上传成功!路径:"+savePath+"/"+newFileName);  
                                out.print(savePath+"/"+newFileName);  
                            }catch(Exception e){  
                                e.printStackTrace();  
                            }  
                        }else {  
                            String filedName = item.getFieldName();  
                            System.out.println("===============");   
                            System.out.println(new String(item.getString().getBytes("iso-8859-1"),
                                    "utf-8"));  
                            System.out.println("FieldName:"+filedName);  
                            // 获得裁剪部分的坐标和宽高
                            System.out.println("String:"+item.getString());  
                        }             
                    }   
                      
                } catch (FileUploadException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
                out.flush();  
                out.close();         
        }

    效果图:

  • 相关阅读:
    SpringMVC,3种不同的URL路由配置方法(这根本不是一个小问题)
    PHP在Windows下安装配置第一步
    跟我一起学extjs5(18--模块的新增、改动、删除操作)
    html image -- data:image/png;base64
    oc66--代理模式应用2
    oc65--协议应用1,接口.做数据类型限定
    oc64--协议2@protocol
    oc63--协议@protocol1
    oc62--block1
    oc61--block
  • 原文地址:https://www.cnblogs.com/tohxyblog/p/6890044.html
Copyright © 2011-2022 走看看