package com.lovobook.RandomCodeServlet;
import java.io.File;
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;
import org.omg.CORBA.PUBLIC_MEMBER;
//上传文件处理
/**
* Servlet implementation class UpLoadSevLet
*/
@WebServlet("/UpLoadSevLet.do")
//使用注解@MultipartConfig开启Servlet对上传文件的支持
//这就打开了上传文件的功能
@MultipartConfig
public class UpLoadSevLet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpLoadSevLet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// 获取上传文件的集合(part类是Servlet3.0新特性封装的上传文件类)
Collection<Part> parts =request.getParts();
if (parts.size()==1) {//单文件
// 获取part文件对象
Part part=request.getPart("file");
// 获取协议 头文件描述信息(Servlet3.0没有获取文件名的方法,需要从请求头文件描述中解析出来)
String fileName=getFlieName(part);
// 保存抄做
part.write(getwebContentpath("weekendWork")+"uploadFile\\"+fileName);
//上传多文件
}else if (parts.size()>1) {
for (Part part :parts) {
//获取协议 头文件描述信息(Servlet3.0没有获取文件名的方法,需要从请求头文件描述中解析出来)
String fileName=getFlieName(part);
// 保存抄做 weekendWork工程名
part.write(getwebContentpath("weekendWork")+"uploadFile\\"+fileName);
}
}else {
System.out.println("没有文件");
}
PrintWriter out=response.getWriter();
out.println("上传成功");
out.close();
}
// 获取上传文件名
public String getFlieName(Part part){
// 获取上传文件的请求头的信息
String header =part.getHeader("content-disposition");
// 截断字符串返回的
String[] tempArr1 =header.split(";");
String[] tempArr2 =tempArr1[2].split("=");
// 获取文件名(兼容各种浏览器)
String fileName =tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")
+1).replaceAll("\"", "");
return fileName;
}
// 获取web根路径把文件放在我建的文件里去用
public String getwebContentpath(String projectName){
String path =Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.err.println(path);
// .metadata这个是eclipse里面默认的复制路径的开头文字
int num= path.indexOf(".metadata");
// WebContent工程里面的自带文件
String webContentpath=path.substring(1, num).replace(‘/‘, ‘\\‘)+projectName+"\\WebContent\\";
return webContentpath;
}