jsp页面form向后台提交file、text以及后台的获取和中文的处理

    在我们的web开发中,很多的时候都需要把本机的一些文件上传到web服务器上面去,,我们可以使用一些已有的组件帮助我们实现这种上传功能。如果表单使用enctype="multipart/form-data"方式提交,
那么一般的request.getParameter(arg0)方法是无法获取Form参数的,
发现使用apache的common-fileupload组件可以获取,但要注意输入参数中中文获取的处理。另外,异步上传可以考虑使用文件上传工具——uploadify。

    常用的上传组件:  

    Apache 的 Commons FileUpload

    JavaZoom的UploadBean

    jspSmartUpload

    FileUpload下载地址:

  http://commons.apache.org/fileupload/

  下载:commons-fileupload-1.2.2-bin.zip    得到:commons-fileupload-1.2.2.jar

  http://commons.apache.org/io/

  下载:commons-io-1.4-bin.zip       得到:commons-io-1.4.jar

1.jsp页面代码-areaBroadcast.jsp

<%@ page language="java" pageEncoding="utf-8" %>

<%  // Get parameters
    boolean isSuccess = ParamUtils.getBooleanParameter(request,"isSuccess");
    boolean send = ParamUtils.getBooleanParameter(request,"send");
%>

<html>
<head>
<title>按用户省份发广播</title>
<meta name="pageID" content="areaBroadcast"/>
</head>
<body>
<%  
if (send) {
	if (isSuccess) { %>
	    <div class="jive-success" id="jive-success">
	    <table cellpadding="0" cellspacing="0" border="0">
	    <tbody>
	        <tr><td class="jive-icon"><img src="images/success-16x16.gif" width="16" height="16" border="0" alt=""></td>
	        <td class="jive-icon-label">
	        	消息发送成功!
	        </td></tr>
	    </tbody>
	    </table>
	    </div><br>
	<%  } else { %>
		 <div class="jive-success" id="jive-success">
		    <table cellpadding="0" cellspacing="0" border="0">
		    <tbody>
		        <tr><td class="jive-icon"><img src="images/error-16x16.gif" width="16" height="16" border="0" alt=""></td>
		        <td class="jive-icon-label">
		        	消息发送失败!
		        </td></tr>
		    </tbody>
		    </table>
		    </div><br>
	 <% }
} %>

<form action="abservlet" enctype="multipart/form-data" method="post" name="abservlet">
	<div class="jive-contentBox" style="-moz-border-radius: 3px;">
		<table cellpadding="3" cellspacing="1" border="0" width="600">
		<tr>
			<td class="jive-label">
				标题:
			</td>
			<td>
			  <input name="title" type="text" style="width: 406px"></input>
			</td>
		</tr>
		<tr>
			<td class="jive-label">
				图片:
			</td>
			<td>
			  <input name="img" type="file"></input>
			</td>
		</tr>
		</table>
	</div>

<input type="submit" value="send">
<input type="submit" name="cancel" value="cancel">
</form>

<script language="JavaScript" type="text/javascript">
setTimeout(function(){
    var js = document.getElementById('jive-success');
    if(js != null) {
    	js.style.display = 'none';
    }
}, 1000);
</script>


</body>
</html>

2.servlet-AreaBroadcastServlet.java

  private static final String imgPath = "/data/ofcache/";
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    {
    	try{
	    	List items = null;
	    	File newFile = null;
	    	String title = null;
               /*建立上传文件的文件夹*/
	    	File dir = new File(imgPath);
	    	 if (!dir.exists())  
	         {
	             dir.mkdirs();  
	         } 
	    	DiskFileUpload upload = new DiskFileUpload();
/*设置获取参数编码,下面get的时候也要设置否则无效。注意:由于前台jsp页面提交的时候使用的格式是enctype="multipart/form-data"输入参数以二进制的形式传输,在输入参数有中文时即使前台jsp页面设定为utf-8格式,后台若不设定获取参数的类型,则用后台得到的中文若打印出来可正常显示,但直接用来当做数据库的查询条件则会出现查询不到数据的情况,且将此中文直接发送给客户端时会出现无法识别的乱码的情况(当时测试结果是windows7下没问题,但是linux环境下会有问题)*/
                upload.setHeaderEncoding("UTF-8");
	    	try {
		        items = upload.parseRequest(request);
		    }
		    catch (Exception e) {
		    	e.printStackTrace();
		    }
		    if (items != null) {
		        for (Object item : items) {
		            FileItem fileItem = (FileItem) item;
		            String fieldName = fileItem.getFieldName();
		             if ("title".equals(fieldName)) {
                                title = fileItem.getString("UTF-8");
		            }
		            /*处理img文件*/
		            if (!fileItem.isFormField()) {
		                if ("img".equals(fieldName)) {
		                    String filename = fileItem.getName();
		                    filename = new File(filename).getName();
		                    byte[] data = fileItem.get();
		                    if (filename != null && filename.trim().length() > 0) {
		                        // Write out Client to dir.
		                    	newFile = new File(dir, filename);
		                        FileOutputStream faos = new FileOutputStream(newFile);
		                        faos.write(data);
		                        faos.flush();
		                        faos.close();
		                    }
	
		                }
		            }
		        }
		    }
	       boolean isSuccess = plugin.sendMsg(title, newFile);
	       response.setContentType("text/html");
	       PrintWriter out = response.getWriter();
		   response.sendRedirect("areaBroadcast.jsp?isSuccess=" + isSuccess + "&send=true");
		   out.flush();
		   out.close();
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }

 
 
 
 
 
 
 
 

3.web.xml

<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <!-- Servlets -->
    <servlet>
        <servlet-name>AreaBroadcastServlet</servlet-name>
        <servlet-class>com.channelsoft.openfire.plugin.AreaBroadcastServlet</servlet-class>
    </servlet>

    <!-- Servlet mappings -->
    <servlet-mapping>
        <servlet-name>AreaBroadcastServlet</servlet-name>
        <url-pattern>/abservlet</url-pattern>
    </servlet-mapping>
    
</web-app>
相关文章
相关标签/搜索