Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Servlet:实现多个文件上传,上传中文文件乱码解决办法

$
0
0

首先,建议将编码设置为GB2312,并在WEB-INF\lib里导入:commons-fileupload-1.3.jar和commons-io-2.4.jar,可百度下下载,然后你编码完成后,上传时可能会遇到"servlet Bad version number in .class file"错误。

解决:

1.Window --> Preferences -->Java --> compiler中的compiler compliance level对应的下拉菜单中选择JDK版本.

2.Window --> Preferences -->MyEclipse --> Servers-->Tomcat --> Tomcat n.x -->JDK中的Tomcat JDKname下的下拉菜单中选择自己电脑上安装的JDK版本(必须与步骤1中的JDK版本一致).

如果还是没有解决,不用着急,因为有些MyEclipse版本自带有JDK版本,所以也要将它改过来.

3.Window --> Preferences -->Java -->Installed JRES,然后在右边选择与步骤1和2版本一致的JDK版本,如果没有,可以自己添加.然后选中就可以了.

4、.Window --> Preferences -->MyEclipse --> Servers-Resin 3-Resin 3.x-JDK-Resin jdk name:选择jdk1.6.0_03


接下来,我们来编码,实现多个文件上传

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
  </head>
  
  <body style="margin:50px">
  <form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
     <p>上传文件:</p>
     文件1:<input type="file" name="file1" /><br/>
     描述:<input type="text" name="description1" /><br/>
     文件2:<input type="file" name="file2" /><br/>
    描述:<input type="text" name="description2" /><br/>
  <input type="submit" value=" 上  传 " />  
  </form>
  </body>
  </html>


com.xieyuan.ServletUpload.java

package com.xieyuan;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFormat.Encoding;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UploadServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}


	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
         response.setCharacterEncoding("GB2312");
         response.getWriter().println("<script>alert('请用POST方式上传文件!')</script>");
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		File file=null;
		String description=null;
		
		String uploadPath=this.getServletContext().getRealPath("upload");
		String uploadTemp=this.getServletContext().getRealPath("upload/temp");
	    //设置响应格式(不设置请求格式,因为文件是二进制的,不能使用UTF-8格式化)
		response.setContentType("text/html;charset=gb2312");
		
		PrintWriter out=response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("<HEAD><TITLE>文件上传</TITLE></HEAD>");
		out.println("<BODY style='margin:50px'>");
		out.println("上传日志:<BR/>");
		//创建基于磁盘的工厂,针对大文件,临时文件将存储在磁盘
		DiskFileItemFactory factory=new DiskFileItemFactory();
		//设置缓冲区大小,超出该文件直接写入到磁盘的大小设置门槛。
		factory.setSizeThreshold(10240);  //这里默认10KB
		//设置用于大于配置的大小阈值设置的临时存储文件目录。
		factory.setRepository(new File(uploadTemp));
		//创建一个文件上传的句柄
		ServletFileUpload upload=new ServletFileUpload(factory);
		//设置最大文件尺寸 ,这里是4MB
		upload.setSizeMax(4194304);
		upload.setHeaderEncoding("GB2312");
		
		try {
			//将解析结果放在LIST中
			List<FileItem> list =upload.parseRequest(request);
			out.println("遍历所有的 FileItem ... <br/>");
			// 遍历 list 中所有的 FileItem
			for(FileItem item:list)
			{
				// 如果是 文本域
				if(item.isFormField())
				{
					if(item.getFieldName().equals("description1")||item.getFieldName().equals("description2"))
					{
											
						description = item.getString("GB2312");	
						out.println("遍历到 "+item.getFieldName()+" ... <br/>"+description+"<BR/>");	
					}
				}
				else 
				{
					//否则为文件域,当getName为Null说明没有选则文件
					if((item.getFieldName().equals("file1")||item.getFieldName().equals("file2"))
							&&item.getName()!=null&&!item.getName().equals(""))
					{
						try 
						{
						
							File remoteFile=new File(item.getName());
							out.println("遍历到 file ... <br/>");
							out.println("客户端文件位置: " + remoteFile.getAbsolutePath() + "<br/>");
							// 服务器端文件,放在 upload 文件夹下
							file=new File(uploadPath,remoteFile.getName());
							if(!file.getParentFile().exists())
								file.getParentFile().mkdirs();
							if(!file.exists())
								file.createNewFile();
							
							item.write(file);
							
						} catch (Exception e) {
							
						}
						finally //总是立即删除保存表单字段内容的临时文件
						{
							item.delete();
						}
					}
				}
			}
			out.println("Request 解析完毕,文件上传完毕!");
		} catch (Exception e) {
			out.println("Request 解析异常!"+e.getMessage());
		}
		out.flush();
		out.close();
	}

	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.xieyuan.UploadServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/servlet/UploadServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>

这样上传文件不会乱码。深入参看,剖析Commons-fileupload.jar上传原理,解决中文乱码原因,请看:

http://download.csdn.net/detail/ab6326795/6219065

张孝祥写的


作者:ab6326795 发表于2013-9-5 22:49:44 原文链接
阅读:57 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles