Servlet3.0新特性之文件上传

HttpServletRequest增加了对文件上传的支持。

HttpServletRequest提供了如下两个方法来处理文件上传:

Part getPart(String name):根据名称来获取文件上传域。

Collection getParts():获取所有文件上传域。


package com.xxx.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name="upload",urlPatterns="/upload")
@MultipartConfig  //部署servlet上传文件
public class UploadServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=GBK");
		PrintWriter out=response.getWriter();
		//获取普通请求参数
		String fileName=request.getParameter("name");
		//获取文件上传域
		Part part=request.getPart("file");
		//获取上传文件的类型
		out.println("上传文件的类型为"+part.getContentType());
		//获取上传文件的大小
		out.println("上传文件的大小为:"+part.getSize());
		//获取该文件上传域的header Name
		Collection headerNames=part.getHeaderNames();
		for(String headerName:headerNames){
			out.println(headerName+"--->"+part.getHeader(headerName));
		}
		
		//将上传文件写到服务器
		part.write(getServletContext().getRealPath("uploadFiles")+"/"+fileName);//项目根目录下的uploadFiles目录
	}
}

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>




  

    My JSP 'upload.jsp' starting page

  
  
  
    




也可以通过web.xml配置文件上传:

 
 	upload
 	com.xxx.action.UploadServlet
 	
 
 
 	upload
 	/upload
 











你可能感兴趣的:(Servlet3.0新特性之文件上传)