zoukankan      html  css  js  c++  java
  • java实现文件上传

    最近自己在做一个小系统玩的时候涉及到了文件的上传,于是在网上找到Java上传文件的方案,最后确定使用common-fileupload实现上传操作。

    • 需求说明

    用户添加页面有一个“上传”按钮,点击按钮弹出上传界面,上传完成后关闭上传界面。

    • 所需Jar包

    commons.fileupload-1.2.0.jar、commons.logging-1.1.1.jar、commons.beanutils-1.8.0.jar、commons.collections-3.2.0.jar、commons.io-1.4.0.jar、commons.lang-2.1.0.jar

    • 实现效果

    •  代码实现
    首先编写核心代码,Javascript打开上传页面,并且从上传页获取返回参数,最后数据返回给回调函数callback:
    Js代码 复制代码 收藏代码
    1. /** 
    2.  * 跳转到上传页 
    3.  * functionId:功能ID 
    4.  * fileType:文件类型 
    5.  * maxSize:文件容量上限 
    6.  * callback:回调函数,返回三个参数:文件真名、文件存放名和文件大小 
    7.  */  
    8. function openUpload(functionId,fileType,maxSize,callback){  
    9.     var url = root+"/CommonController.jhtml?method=goFileUpload&";  
    10.     if(functionId!=null){  
    11.         url = url + "functionId="+functionId+"&";  
    12.     }  
    13.     if(fileType!=null){  
    14.         url = url + "fileType="+fileType+"&";  
    15.     }  
    16.     if(maxSize!=null){  
    17.         url = url + "maxSize="+maxSize;  
    18.     }  
    19.     var win = window.showModalDialog(url,"","dialogWidth:300px;dialogHeight:150px;scroll:no;status:no");  
    20.     if(win != null){  
    21.         var arrWin = win.split(",");  
    22.         callback(arrWin[0],arrWin[1],arrWin[2]);  
    23.     }  
    24. }  
    /**
     * 跳转到上传页
     * functionId:功能ID
     * fileType:文件类型
     * maxSize:文件容量上限
     * callback:回调函数,返回三个参数:文件真名、文件存放名和文件大小
     */
    function openUpload(functionId,fileType,maxSize,callback){
    	var url = root+"/CommonController.jhtml?method=goFileUpload&";
    	if(functionId!=null){
    		url = url + "functionId="+functionId+"&";
    	}
    	if(fileType!=null){
    		url = url + "fileType="+fileType+"&";
    	}
    	if(maxSize!=null){
    		url = url + "maxSize="+maxSize;
    	}
    	var win = window.showModalDialog(url,"","dialogWidth:300px;dialogHeight:150px;scroll:no;status:no");
    	if(win != null){
    		var arrWin = win.split(",");
    		callback(arrWin[0],arrWin[1],arrWin[2]);
    	}
    }

      用户添加页面相关代码,点击“上传”按钮时调用上面的核心js代码,并且获取返回值

    Html代码 复制代码 收藏代码
    1. <script>  
    2. .......  
    3.   
    4. function openUpload_(){  
    5.     openUpload(null,'JPG,GIF,JPEG,PNG','5',callback);  
    6. }  
    7.   
    8. /**  
    9.  * 回调函数,获取上传文件信息  
    10.  * realName真实文件名  
    11.  * saveName文件保存名  
    12.  * maxSize文件实际大小  
    13.  */  
    14. function callback(realName,saveName,maxSize){  
    15.     $("#photo_").val(saveName);  
    16.     //回调后其它操作  
    17. }  
    18. </script>  
    19.   
    20. <tr>  
    21.             <td>头像:</td>  
    22.             <td>  
    23.                 <input type="hidden" name="photo" id="photo_"></input>  
    24.                 <input type="button" onclick="openUpload_()" value="上传"/>  
    25.             </td>  
    26.         </tr>  
    <script>
    .......
    
    function openUpload_(){
    	openUpload(null,'JPG,GIF,JPEG,PNG','5',callback);
    }
    
    /**
     * 回调函数,获取上传文件信息
     * realName真实文件名
     * saveName文件保存名
     * maxSize文件实际大小
     */
    function callback(realName,saveName,maxSize){
    	$("#photo_").val(saveName);
    	//回调后其它操作
    }
    </script>
    
    <tr>
    			<td>头像:</td>
    			<td>
    				<input type="hidden" name="photo" id="photo_"></input>
    				<input type="button" onclick="openUpload_()" value="上传"/>
    			</td>
    		</tr>

      文件上传的JSP代码,需要注意的是在head标签内添加<base target="_self">以防止页面跳转时弹出新窗口,用户选择指定文件,点击上传时就提交表单访问指定后台代码

    Html代码 复制代码 收藏代码
    1. <%@ include file="/WEB-INF/jsp/header.jsp" %>  
    2. <%@ page language="java" contentType="text/html; charset=UTF-8"  
    3.     pageEncoding="UTF-8"%>  
    4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    5. <html>  
    6. <head>  
    7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
    8. <meta http-equiv="pragma" content="no-cache" />  
    9. <base target="_self">  
    10. <title>文件上传</title>  
    11. </head>  
    12. <body>  
    13.     <h5>文件上传</h5><hr/>  
    14.     <form id="file_upload_id" name="file_upload_name" action="<%=root%>/CommonController.jhtml?method=doFileUpload" method="post" enctype="multipart/form-data">  
    15.         <input type="hidden" name="functionId" value="${functionId}"/>  
    16.         <input type="hidden" name="fileType" value="${fileType}"/>  
    17.         <input type="hidden" name="maxSize" value="${maxSize}"/>  
    18.         <div><input type="file" name="file_upload"/></div>  
    19.         <c:if test="${maxSize!=null}">  
    20.             <div style="font: 12">文件最大不能超过${maxSize}MB</div>  
    21.         </c:if>  
    22.         <c:if test="${fileType!=null}">  
    23.             <div style="font: 12">文件格式必须是:${fileType}</div>  
    24.         </c:if>  
    25.         <div><input type="submit" value="上传"/></div>  
    26.     </form>  
    27. </body>  
    28. </html>  
    <%@ include file="/WEB-INF/jsp/header.jsp" %>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <meta http-equiv="pragma" content="no-cache" />
    <base target="_self">
    <title>文件上传</title>
    </head>
    <body>
    	<h5>文件上传</h5><hr/>
    	<form id="file_upload_id" name="file_upload_name" action="<%=root%>/CommonController.jhtml?method=doFileUpload" method="post" enctype="multipart/form-data">
    		<input type="hidden" name="functionId" value="${functionId}"/>
    		<input type="hidden" name="fileType" value="${fileType}"/>
    		<input type="hidden" name="maxSize" value="${maxSize}"/>
    		<div><input type="file" name="file_upload"/></div>
    		<c:if test="${maxSize!=null}">
    			<div style="font: 12">文件最大不能超过${maxSize}MB</div>
    		</c:if>
    		<c:if test="${fileType!=null}">
    			<div style="font: 12">文件格式必须是:${fileType}</div>
    		</c:if>
    		<div><input type="submit" value="上传"/></div>
    	</form>
    </body>
    </html>

      CommonController目前有两个方法,一个是跳转到上传页面的方法,一个是执行上传操作的方法doFileUpload,上传方法运行的大概逻辑是:首先获取页面的请求参数,fileType用于限制上传文件格式,

    maxSize用于限制上传文件最大值,随后创建上传目录上传即可。

    Java代码 复制代码 收藏代码
    1. public class CommonController extends BaseController {  
    2.     Log log = LogFactory.getLog(CommonController.class);  
    3.       
    4.     Properties fileUploadPro = null;  
    5.     public CommonController(){  
    6.         fileUploadPro = PropertiesUtil.getPropertiesByClass("fileupload.properties");  
    7.     }  
    8.       
    9.       
    10.     @Override  
    11.     public ModeAndView init(HttpServletRequest request,  
    12.             HttpServletResponse response) throws ServletException, IOException {  
    13.           
    14.         return null;  
    15.     }  
    16.       
    17.     /** 
    18.      * 跳转到文件上传页 
    19.      * @param request 
    20.      * @param response 
    21.      * @return 
    22.      * @throws ServletException 
    23.      * @throws IOException 
    24.      */  
    25.     public ModeAndView goFileUpload(HttpServletRequest request,  
    26.             HttpServletResponse response) throws ServletException, IOException {  
    27.         String functionId = request.getParameter("functionId");  
    28.         String fileType = request.getParameter("fileType");  
    29.         String maxSize = request.getParameter("maxSize");  
    30.         ModeAndView mav = new ModeAndView("/WEB-INF/jsp/common/fileUpload.jsp");  
    31.           
    32.         if(functionId!=null && !"".equals(functionId.trim())){  
    33.             mav.addObject("functionId", functionId);  
    34.         }  
    35.         if(fileType!=null && !"".equals(fileType.trim())){  
    36.             mav.addObject("fileType", fileType);  
    37.         }  
    38.         if(maxSize!=null && !"".equals(maxSize.trim())){  
    39.             mav.addObject("maxSize", maxSize);  
    40.         }  
    41.         return mav;  
    42.     }  
    43.       
    44.     /** 
    45.      * 上传文件 
    46.      * @param request 
    47.      * @param response 
    48.      * @return 
    49.      * @throws ServletException 
    50.      * @throws IOException 
    51.      */  
    52.     @SuppressWarnings("unchecked")  
    53.     public ModeAndView doFileUpload(HttpServletRequest request,  
    54.             HttpServletResponse response) throws ServletException, IOException {  
    55.         //获取并解析文件类型和支持最大值  
    56.         String functionId = request.getParameter("functionId");  
    57.         String fileType = request.getParameter("fileType");  
    58.         String maxSize = request.getParameter("maxSize");  
    59.           
    60.         //临时目录名  
    61.         String tempPath = fileUploadPro.getProperty("tempPath");  
    62.         //真实目录名  
    63.         String filePath = fileUploadPro.getProperty("filePath");  
    64.           
    65.         FileUtil.createFolder(tempPath);  
    66.         FileUtil.createFolder(filePath);  
    67.           
    68.         DiskFileItemFactory factory = new DiskFileItemFactory();  
    69.         //最大缓存  
    70.         factory.setSizeThreshold(5*1024);  
    71.         //设置临时文件目录  
    72.         factory.setRepository(new File(tempPath));  
    73.         ServletFileUpload upload = new ServletFileUpload(factory);  
    74.         if(maxSize!=null && !"".equals(maxSize.trim())){  
    75.             //文件最大上限  
    76.             upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);  
    77.         }  
    78.           
    79.         try {  
    80.             //获取所有文件列表  
    81.             List<FileItem> items = upload.parseRequest(request);  
    82.             for (FileItem item : items) {  
    83.                 if(!item.isFormField()){  
    84.                     //文件名  
    85.                     String fileName = item.getName();  
    86.                       
    87.                     //检查文件后缀格式  
    88.                     String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();  
    89.                     if(fileType!=null && !"".equals(fileType.trim())){  
    90.                         boolean isRealType = false;  
    91.                         String[] arrType = fileType.split(",");  
    92.                         for (String str : arrType) {  
    93.                             if(fileEnd.equals(str.toLowerCase())){  
    94.                                 isRealType = true;  
    95.                                 break;  
    96.                             }  
    97.                         }  
    98.                         if(!isRealType){  
    99.                             //提示错误信息:文件格式不正确  
    100.                             super.printJsMsgBack(response, "文件格式不正确!");  
    101.                             return null;  
    102.                         }  
    103.                     }  
    104.                       
    105.                     //创建文件唯一名称  
    106.                     String uuid = UUID.randomUUID().toString();  
    107.                     //真实上传路径  
    108.                     StringBuffer sbRealPath = new StringBuffer();  
    109.                     sbRealPath.append(filePath).append(uuid).append(".").append(fileEnd);  
    110.                     //写入文件  
    111.                     File file = new File(sbRealPath.toString());  
    112.                     item.write(file);  
    113.                     //上传成功,向父窗体返回数据:真实文件名,虚拟文件名,文件大小  
    114.                     StringBuffer sb = new StringBuffer();  
    115.                     sb.append("window.returnValue='").append(fileName).append(",").append(uuid).append(".").append(fileEnd).append(",").append(file.length()).append("';");  
    116.                     sb.append("window.close();");  
    117.                     super.printJsMsg(response, sb.toString());  
    118.                     log.info("上传文件成功,JS信息:"+sb.toString());  
    119.                 }//end of if  
    120.             }//end of for  
    121.               
    122.         }catch (Exception e) {  
    123.             //提示错误:比如文件大小  
    124.             super.printJsMsgBack(response, "上传失败,文件大小不能超过"+maxSize+"M!");  
    125.             log.error("上传文件异常!",e);  
    126.             return null;  
    127.         }  
    128.           
    129.         return null;  
    130.     }  
    131. }  
    public class CommonController extends BaseController {
    	Log log = LogFactory.getLog(CommonController.class);
    	
    	Properties fileUploadPro = null;
    	public CommonController(){
    		fileUploadPro = PropertiesUtil.getPropertiesByClass("fileupload.properties");
    	}
    	
    	
    	@Override
    	public ModeAndView init(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		
    		return null;
    	}
    	
    	/**
    	 * 跳转到文件上传页
    	 * @param request
    	 * @param response
    	 * @return
    	 * @throws ServletException
    	 * @throws IOException
    	 */
    	public ModeAndView goFileUpload(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String functionId = request.getParameter("functionId");
    		String fileType = request.getParameter("fileType");
    		String maxSize = request.getParameter("maxSize");
    		ModeAndView mav = new ModeAndView("/WEB-INF/jsp/common/fileUpload.jsp");
    		
    		if(functionId!=null && !"".equals(functionId.trim())){
    			mav.addObject("functionId", functionId);
    		}
    		if(fileType!=null && !"".equals(fileType.trim())){
    			mav.addObject("fileType", fileType);
    		}
    		if(maxSize!=null && !"".equals(maxSize.trim())){
    			mav.addObject("maxSize", maxSize);
    		}
    		return mav;
    	}
    	
    	/**
    	 * 上传文件
    	 * @param request
    	 * @param response
    	 * @return
    	 * @throws ServletException
    	 * @throws IOException
    	 */
    	@SuppressWarnings("unchecked")
    	public ModeAndView doFileUpload(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		//获取并解析文件类型和支持最大值
    		String functionId = request.getParameter("functionId");
    		String fileType = request.getParameter("fileType");
    		String maxSize = request.getParameter("maxSize");
    		
    		//临时目录名
    		String tempPath = fileUploadPro.getProperty("tempPath");
    		//真实目录名
    		String filePath = fileUploadPro.getProperty("filePath");
    		
    		FileUtil.createFolder(tempPath);
    		FileUtil.createFolder(filePath);
    		
    		DiskFileItemFactory factory = new DiskFileItemFactory();
    		//最大缓存
    		factory.setSizeThreshold(5*1024);
    		//设置临时文件目录
    		factory.setRepository(new File(tempPath));
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		if(maxSize!=null && !"".equals(maxSize.trim())){
    			//文件最大上限
    			upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);
    		}
    		
    		try {
    			//获取所有文件列表
    			List<FileItem> items = upload.parseRequest(request);
    			for (FileItem item : items) {
    				if(!item.isFormField()){
    					//文件名
    					String fileName = item.getName();
    					
    					//检查文件后缀格式
    					String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
    					if(fileType!=null && !"".equals(fileType.trim())){
    						boolean isRealType = false;
    						String[] arrType = fileType.split(",");
    						for (String str : arrType) {
    							if(fileEnd.equals(str.toLowerCase())){
    								isRealType = true;
    								break;
    							}
    						}
    						if(!isRealType){
    							//提示错误信息:文件格式不正确
    							super.printJsMsgBack(response, "文件格式不正确!");
    							return null;
    						}
    					}
    					
    					//创建文件唯一名称
    					String uuid = UUID.randomUUID().toString();
    					//真实上传路径
    					StringBuffer sbRealPath = new StringBuffer();
    					sbRealPath.append(filePath).append(uuid).append(".").append(fileEnd);
    					//写入文件
    					File file = new File(sbRealPath.toString());
    					item.write(file);
    					//上传成功,向父窗体返回数据:真实文件名,虚拟文件名,文件大小
    					StringBuffer sb = new StringBuffer();
    					sb.append("window.returnValue='").append(fileName).append(",").append(uuid).append(".").append(fileEnd).append(",").append(file.length()).append("';");
    					sb.append("window.close();");
    					super.printJsMsg(response, sb.toString());
    					log.info("上传文件成功,JS信息:"+sb.toString());
    				}//end of if
    			}//end of for
    			
    		}catch (Exception e) {
    			//提示错误:比如文件大小
    			super.printJsMsgBack(response, "上传失败,文件大小不能超过"+maxSize+"M!");
    			log.error("上传文件异常!",e);
    			return null;
    		}
    		
    		return null;
    	}
    }

      至此一个文件上传即已实现,而且能够基本满足不同模块的上传通用性,我还留着个functionId参数用于以后针对不同模块上传文件到不同目录。

    2018年7月28日,绝望到明白人活着只能靠自己; 2018年7月29日,告诉她一切,还对我不离不弃。 从此,走技术路线,改变生活。
  • 相关阅读:
    用 .Net WebBrowser 控件获取POST数据
    yield再理解--绝对够透彻
    Keras 和 PyTorch 的对比选择
    Keras -Python编写的开源人工神经网络库
    Python 加密之 生成pyd文件
    FPN全解-特征金字塔网络
    RetinaNet(Focal Loss)
    Focal Loss for Dense Object Detection(Retina Net)
    ImageNet Classification-darknet
    Darknet
  • 原文地址:https://www.cnblogs.com/outlooking/p/4234621.html
Copyright © 2011-2022 走看看