Servlet处理POST上传的文件

WEB文件上传也是采用POST的方式。不过需要将FORM的enctype属性设置为:multipart/form-data。由于上传的文件会比较大,因此需要设置该参数指定浏览器使用二进制上传。如果不设置,enctype属性默认是application/x-www-form-urlencoded,浏览器将使用ASCII向服务器发送数据,导致发送文件失败。

上传文件使用文件域(<input type="file">),并把FORM的Enctype设置为multipart/form/data。

工程结构如下:



























以下是上传文件的客户端代码:upload.html。

<!DOCTYPE html>
<html>
  <head>
    <title>upload.html</title>
	<meta http-equiv="content-type" content="text/html";charset="UTF-8" >

  </head>
  
  <body>
    <form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
    	<div align="center">
    		<fieldset style="width:80%">
    			<legend>上传文件</legend><br/>
    			<div class='line'>
    				<div align='left' class="leftDiv">上传文件一</div>
    				<div align='left' class="rightDiv">
    					<input type="file" name="file1" class="text">
    				</div>
    			</div>
    			<div class='line'>
    				<div align='left' class="leftDiv">上传文件二</div>
    				<div align='left' class="rightDiv">
    					<input type="file" name="file2" class="text">
    				</div>
    			</div>
    			<div class='line'>
    				<div align='left' class="leftDiv">上传文件说明一</div>
    				<div align='left' class="rightDiv">
    					<input type="text" name="description1" class="text">
    				</div>
    			</div>
    			<div class='line'>
    				<div align='left' class="leftDiv">上传文件说明二</div>
    				<div align='left' class="rightDiv">
    					<input type="text" name="description2" class="text">
    				</div>
    			</div>
    			<div class='line'>
    				<div align='left' class="leftDiv">上传文件说明二</div>
    				<div align='left' class="rightDiv">
    					<input type="submit" value=" 上传文件" class="button">
    				</div>
    			</div>
    		</fieldset>
    	</div>
    </form>
  </body>
</html>
运行结果如下:

上传文件服务器端:

由于上传文件时浏览器是以二进制的方式发送数据,因此Servlet里不能简单的通过HttpServletRequest的getParameter()方法。要想获取内容,就必须更具HTTP协议所规定的的格式解析浏览器提交的Request。

这里,使用Apache开源的jar包。Commons Fileupload是Apache commons众多开源组件中的一员。可以从Apache网站中进行下载:

注意:虽然编码过程只用到:commons-fileupload-1.3.2.jar包,但是运行过程必须用到commons-io-2.5.jar包,两者缺一不可!

将这两个包放到/WEB-INF/lib下。

UploadServlet的源码如下:

package com.hello.firstweb;

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 org.apache.commons.io.IOUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
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("UTF-8");
		response.getWriter().println("请以POST方式上传文件");
		
	}

	/**
		 * 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
		 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		File file1 = null , file2 = null;
		String description1 = null,description2=null;
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//输出到客户端浏览器
		out.println("<HTML>");
		out.println("<meta http-equiv=\"content-type\" content=\"text/html\";charset=\"UTF-8\">");
		DiskFileUpload diskFileUpload = new DiskFileUpload(); //解析request
		try{
			List<FileItem> list = diskFileUpload.parseRequest(request);
			out.println("遍历所有的 FileItem ...<br/>");
			for(FileItem fileItem:list){
				if(fileItem.isFormField()){
					if("description1".equals(fileItem.getFieldName())){
						out.println("遍历到 description1...<br/>");	
						description1 = new String(fileItem.getString().getBytes(),"UTF-8");
					}
					if("description2".equals(fileItem.getFieldName())){
						out.println("遍历到 description2...<br/>");	
						description2 = new String(fileItem.getString().getBytes(),"UTF-8");
					}
				}
				else{
					if("file1".equals(fileItem.getFieldName())){
						File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
						out.println("遍历到file1...<br/>");
						out.println("客户端文件位置: "+remoteFile.getAbsolutePath()+"<br/>");
						//服务器端文件,放在upload文件夹下面
						file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
						file1.getParentFile().mkdirs();  //创建文件夹路径
						file1.createNewFile(); //创建新文件
						
						InputStream ins = fileItem.getInputStream();   //FileItem的内容
						OutputStream ous = new FileOutputStream(file1); //输出到file1中
						try{
							byte[] buffer = new byte[1024]; //缓冲字节
							int len = 0;
							while((len = ins.read(buffer))>-1)
								ous.write(buffer, 0, len);
								out.println("已保存文件"+file1.getAbsolutePath()+"<br/>");
						}finally{
							ous.close();
							ins.close();
						}
					}
					if("file2".equals(fileItem.getFieldName())){
						File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
						out.println("遍历到file2...<br/>");
						out.println("客户端文件位置: "+remoteFile.getAbsolutePath()+"<br/>");
						//服务器端文件,放在upload文件夹下面
						file2 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
						file2.getParentFile().mkdirs();  //创建文件夹路径
						file2.createNewFile(); //创建新文件
						
						InputStream ins = fileItem.getInputStream();   //FileItem的内容
						OutputStream ous = new FileOutputStream(file2); //输出到file1中
						try{
							byte[] buffer = new byte[1024]; //缓冲字节
							int len = 0;
							while((len = ins.read(buffer))>-1)
								ous.write(buffer, 0, len);
								out.println("已保存文件"+file2.getAbsolutePath()+"<br/>");
						}finally{
							ous.close();
							ins.close();
						}
					}
				}		
			}out.println("Request 解析完毕");
		}catch (FileUploadException e){}
		
		if(file1!=null){   //输出file1链接
			out.println("<div class = 'line'>");
			out.println("  <div align='left' class='leftDiv'>file1:</div>");
			out.println("  <div align='left' class='rightDiv'>");
			out.println("    <a href='"+request.getContextPath()+"/attachment/"+file1.getName()+"' target=_blank>"+file1.getName()+"</a>");
			out.println("   </div>");
			out.println("   </div>");
		}
		
		if(file2!=null){   //输出file1链接
			out.println("<div class = 'line'>");
			out.println("  <div align='left' class='leftDiv'>file1:</div>");
			out.println("  <div align='left' class='rightDiv'>");
			out.println("    <a href='"+request.getContextPath()+"/attachment/"+file2.getName()+"'target=_blank>"+file2.getName()+"</a>");
			out.println("   </div>");
			out.println("   </div>");
		}
		out.println("<div class = 'line'>");
		out.println("  <div align='left' class='leftDiv'>description1:</div>");
		out.println(description1);
		out.println("</div>");
		out.println("</div>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

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

}
选择上传文件之后,运行效果如下:


需要注意的是:上传的文件名中应该避免有中文,否则会出现乱码。上传成功后,可以在D:\WebWorkspace\.metadata\.me_tcat7\webapps\firstWeb\attachment\下面找到,也可以通过上图中的链接直接打开。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值