• 使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能。并且在界面上有radio 的选择内容也要上传


    使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能。并且在界面上有radio 的选择内容也要上传

    uploadify 插件的 下载和文档地址  点击打开链接

    1. jsp的内容

    1. <%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%> 
    2. <
    3. String path = request.getContextPath(); 
    4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
    5. %> 
    6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    7. <html> 
    8. <head> 
    9. <basehref="<%=basePath%>">   
    10. <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"> 
    11. <title>兑换卷查询系统</title> 
    12. <linktype="text/css"href="css/ui-lightness/jquery-ui-1.8.21.custom.css"rel="stylesheet"/> 
    13. <linkhref="css/uploadify.css"rel="stylesheet"type="text/css"/> 
    14.  
    15. <scripttype="text/javascript"src="js/jquery-1.7.2.min.js"></script> 
    16. <scripttype="text/javascript"src="js/jquery.uploadify-3.1.min.js"></script> 
    17.  
    18.  
    19. </head> 
    20.  
    21. <style> 
    22. </style> 
    23.  
    24. <body> 
    25. <form> 
    26.     <divid="fileQueue"></div> 
    27.         <h4>提货券类型</h4> 
    28.                 <inputtype="radio"id="typeCode"name="typeCode"value="108"checked="">108</input> 
    29.                 <inputtype="radio"id="typeCode"name="typeCode"value="138">138</input> 
    30.         </p>       
    31.         <inputtype="file"name="file_upload"id="file_upload"/> 
    32.         <p> 
    33.         <ahref="javascript:$('#file_upload').uploadify('upload','*')">开始上传</a> 
    34.         <script> 
    35.             $(function() { 
    36.                 var typeCode ="";  
    37.                  
    38.                 $("#file_upload").uploadify({ 
    39.                     'buttonText'    :   '选择文件', 
    40.                     'multi'         :   false, 
    41.                     'swf'           :   'html/uploadify.swf', 
    42.                     'uploader'      :   '../servlet/Upload', 
    43.                     'auto'          :   false, 
    44.                     'onUploadStart' :   function(file) { 
    45.                           
    46.                         //校验    
    47.                          
    48.                         $(":input[name='typeCode']").each(function(){                        
    49.                                 if ( $(this).attr("checked")) 
    50.                                     { 
    51.                                         typeCode = ($(this).val()); 
    52.                                     } 
    53.                          }); 
    54.                         $("#file_upload").uploadify("settings", "formData", {'typeCode':typeCode}); 
    55.                     } 
    56.                 }); 
    57.             });  
    58.         </script> 
    59.          
    60.         </p> 
    61.         <!-- <a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上传</a> --> 
    62.         </p> 
    63. </form>    
    64. </body> 
    65. </html> 
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <base href="<%=basePath%>">  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>兑换卷查询系统</title>
    <link type="text/css" href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
    <link href="css/uploadify.css" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.uploadify-3.1.min.js"></script>
    
    
    </head>
    
    <style>
    </style>
    
    <body>
    <form>
    	<div id="fileQueue"></div>
    		<h4>提货券类型</h4>
    				<input type="radio" id="typeCode" name="typeCode" value="108" checked="">108</input>
    				<input type="radio" id="typeCode" name="typeCode" value="138">138</input>
    		</p>		
            <input type="file" name="file_upload" id="file_upload" />
            <p>
            <a href="javascript:$('#file_upload').uploadify('upload','*')">开始上传</a>
            <script>
            	$(function() {
    	        	var typeCode =""; 
    	        	
    		    	$("#file_upload").uploadify({
    		    		'buttonText'    :	'选择文件',
    		    		'multi'    		: 	false,
    		            'swf'      		: 	'html/uploadify.swf',
    		            'uploader' 		: 	'../servlet/Upload',
    		            'auto' 			: 	false,
    		            'onUploadStart' : 	function(file) {
    			        	 
    			        	//校验   
    		                
    	                    $(":input[name='typeCode']").each(function(){	                    
    	                     		if ( $(this).attr("checked"))
    	                     			{
    	                     				typeCode = ($(this).val());
    	                     			}
    	                     });
    			        	$("#file_upload").uploadify("settings", "formData", {'typeCode':typeCode});
    			        }
    		    	});
    			});	
            </script>
            
            </p>
            <!-- <a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上传</a> -->
            </p>
    </form> 	
    </body>
    </html>

    2.java服务器端的程序

    1. package com.alcor.inquire.servlet; 
    2.  
    3. import java.io.File; 
    4. import java.io.IOException; 
    5. import java.util.Iterator; 
    6. import java.util.List; 
    7. import java.util.UUID; 
    8.  
    9. import javax.servlet.ServletException; 
    10. import javax.servlet.http.HttpServlet; 
    11. import javax.servlet.http.HttpServletRequest; 
    12. import javax.servlet.http.HttpServletResponse; 
    13.  
    14. import org.apache.log4j.Logger; 
    15. import org.apache.tomcat.util.http.fileupload.FileItem; 
    16. import org.apache.tomcat.util.http.fileupload.FileUploadException; 
    17. import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; 
    18. import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; 
    19.  
    20.  
    21. publicclass ImportData extends HttpServlet { 
    22.  
    23.     /**
    24.      *
    25.      */ 
    26.     privatestaticfinallong serialVersionUID = 3387249060639006401L; 
    27.      
    28.     privatestaticfinal Logger logger = Logger.getLogger(ImportData.class); 
    29.     publicvoid doGet(HttpServletRequest request, HttpServletResponse response) 
    30.             throws ServletException, IOException { 
    31.         logger.debug("doGet(HttpServletRequest request, HttpServletResponse response)"); 
    32.         String typeCode =""; //兑换卷类型 
    33.          
    34.         String savePath = this.getServletConfig().getServletContext().getRealPath(""); 
    35.         savePath = savePath + "/uploads/"
    36.         File f1 = new File(savePath); 
    37.         System.out.println(savePath); 
    38.         if (!f1.exists()) { 
    39.             f1.mkdirs(); 
    40.         } 
    41.         DiskFileItemFactory fac = new DiskFileItemFactory(); 
    42.         ServletFileUpload upload = new ServletFileUpload(fac); 
    43.         upload.setHeaderEncoding("utf-8"); 
    44.         List<FileItem> fileList = null
    45.         try
    46.             fileList = upload.parseRequest(request); 
    47.         } catch (FileUploadException ex) { 
    48.             return
    49.         } 
    50.         Iterator<FileItem> it = fileList.iterator(); 
    51.         String name = ""
    52.         String extName = ""
    53.         while (it.hasNext()) { 
    54.             FileItem item = it.next(); 
    55.             logger.debug(item.getContentType()); 
    56.             if (!item.isFormField()) { 
    57.                 name = item.getName(); 
    58.                 long size = item.getSize(); 
    59.                 String type = item.getContentType(); 
    60.                 logger.debug("文件名:"+name+",大小:"+size + ",类型:" + type); 
    61.                 if (name == null || name.trim().equals("")) { 
    62.                     continue
    63.                 } 
    64.                 //扩展名格式:   
    65.                 if (name.lastIndexOf(".") >= 0) { 
    66.                     extName = name.substring(name.lastIndexOf(".")); 
    67.                 } 
    68.                 File file = null
    69.                 do
    70.                     //生成文件名: 
    71.                     name = UUID.randomUUID().toString(); 
    72.                     file = new File(savePath + name + extName); 
    73.                 } while (file.exists()); 
    74.                 File saveFile = new File(savePath + name + extName); 
    75.                 try
    76.                     item.write(saveFile); 
    77.                 } catch (Exception e) { 
    78.                     e.printStackTrace(); 
    79.                 } 
    80.             }else 
    81.             { 
    82.                 //获得简单域的名字   
    83.                 String fieldName = item.getFieldName();  
    84.                 if (fieldName.equalsIgnoreCase("typeCode")) 
    85.                 { 
    86.                     //获得简单域的值   
    87.                     String fieldValue = item.getString("UTF-8");  
    88.                     typeCode = fieldValue; 
    89.                     logger.debug("兑换卷类型是:"+typeCode); 
    90.                 } 
    91.                  
    92.             } 
    93.         } 
    94.         response.getWriter().print(name + extName); 
    95.  
    96.     } 
    97.  
    98.     // Process the HTTP Post request 
    99.     publicvoid doPost(HttpServletRequest request, HttpServletResponse response) 
    100.             throws ServletException, IOException { 
    101.         doGet(request, response); 
    102.     } 
    package com.alcor.inquire.servlet;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.log4j.Logger;
    import org.apache.tomcat.util.http.fileupload.FileItem;
    import org.apache.tomcat.util.http.fileupload.FileUploadException;
    import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
    import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
    
    
    public class ImportData extends HttpServlet {
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 3387249060639006401L;
    	
    	private static final Logger logger = Logger.getLogger(ImportData.class);
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		logger.debug("doGet(HttpServletRequest request, HttpServletResponse response)");
    		String typeCode =""; //兑换卷类型
    		
    		String savePath = this.getServletConfig().getServletContext().getRealPath("");
            savePath = savePath + "/uploads/";
            File f1 = new File(savePath);
            System.out.println(savePath);
            if (!f1.exists()) {
                f1.mkdirs();
            }
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(fac);
            upload.setHeaderEncoding("utf-8");
            List<FileItem> fileList = null;
            try {
                fileList = upload.parseRequest(request);
            } catch (FileUploadException ex) {
                return;
            }
            Iterator<FileItem> it = fileList.iterator();
            String name = "";
            String extName = "";
            while (it.hasNext()) {
                FileItem item = it.next();
                logger.debug(item.getContentType());
                if (!item.isFormField()) {
                    name = item.getName();
                    long size = item.getSize();
                    String type = item.getContentType();
                    logger.debug("文件名:"+name+",大小:"+size + ",类型:" + type);
                    if (name == null || name.trim().equals("")) {
                        continue;
                    }
                    //扩展名格式:  
                    if (name.lastIndexOf(".") >= 0) {
                        extName = name.substring(name.lastIndexOf("."));
                    }
                    File file = null;
                    do {
                        //生成文件名:
                        name = UUID.randomUUID().toString();
                        file = new File(savePath + name + extName);
                    } while (file.exists());
                    File saveFile = new File(savePath + name + extName);
                    try {
                        item.write(saveFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else
                {
                	//获得简单域的名字  
                    String fieldName = item.getFieldName(); 
                    if (fieldName.equalsIgnoreCase("typeCode"))
                    {
                    	//获得简单域的值  
                    	String fieldValue = item.getString("UTF-8"); 
                    	typeCode = fieldValue;
                    	logger.debug("兑换卷类型是:"+typeCode);
                    }
                	
                }
            }
            response.getWriter().print(name + extName);
    
    	}
    
    	// Process the HTTP Post request
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    

    3.jsp代码中 如下代码是关键,否则服务端无法获取radio的值

    1. $("#file_upload").uploadify("settings", "formData", {'typeCode':typeCode}); 
  • 相关阅读:
    Java EE部分-- 各框架对比与项目优化
    Java EE部分--Mybatis
    Java EE部分--MVC
    Java EE部分--Hibernate、Struts
    Java EE部分--spring(二)
    Java EE部分--spring(一)
    IO和NIOAIO
    JDK、 反射

    线程(二)
  • 原文地址:https://www.cnblogs.com/jameslif/p/3653819.html
Copyright © 2020-2023  润新知