Servlet3.0新特性之批量上传

package com.xxx.action;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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;

/**
 * 批量上传文件
 * @author Administrator
 *
 */
@WebServlet(name="uploadPart",urlPatterns="/uploadPart")
@MultipartConfig
public class UploadPartServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("GBK");
		resp.setCharacterEncoding("GBK");
		resp.setContentType("text/html;charset=GBK");
		//上传文件存储位置
		String path=this.getServletContext().getRealPath("/WEB-INF/upload");
		Collection parts=req.getParts();
		for(Part part:parts){
			//只处理上传文件区段
            if (part.getName().startsWith("file")) {
            	String header=part.getHeader("content-disposition");
    			//System.out.println(header); //form-data; name="file2"; filename="11.jpg"
    			//String[] strArr=header.split(";");
    			//System.out.println(strArr.length);
    			//String[] tempName=strArr[2].split("=");
    			//String fileNmae=tempName[1].replaceAll("\"", "");
    			//System.out.println(fileNmae);
    			String fileName=getFileName(part);
            	part.write(path+File.separator+fileName);
            }
		}
	}
	
	 private String getFileName(Part part) {
        String header = part.getHeader("Content-Disposition");
        String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
        header.lastIndexOf("\"");
        return fileName;
    }

  
    
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}


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



  
    
    
    My JSP 'upload.jsp' starting page
  
  
  
    






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