public class ReciveServlet extendsHttpServlet {private static final long serialVersionUID = 1LpublicReciveServlet() {super();//TODO Auto-generated constructor stub
}protected voiddoPost(HttpServletRequest request,
HttpServletResponse response)throwsServletException, IOException {//TODO Auto-generated method stub
doGet(request, response);
}protected voiddoGet(HttpServletRequest request,
HttpServletResponse response)throwsServletException, IOException {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
PrintWriter out = response.getWriter();
File file = new File(savePath);
// 判断上传文件的保存目录是否存在
if (!file.exists() && !file.isDirectory()) {
System.out.println(savePath + "目录不存在,需要创建");
// 创建目录
file.mkdir();
}
// 返回值提示
String message = "";
// 创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
try {
// 创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 判断提交上来的数据是否是上传表单的数据
if (!ServletFileUpload.isMultipartContent(request)) {
// 按照传统方式获取数据
return;
}
System.out.println("isM = "+ServletFileUpload.isMultipartContent(request));
// 使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List集合,每一个FileItem对应一个Form表单的输入
List list = upload.parseRequest(request);
for (FileItem item : list) {
// 如果fileitem中封装的是普通输入项的数据
if (item.isFormField()) {
String name = item.getFieldName();
// 转码
String value = item.getString("UTF-8");
value = new String(value.getBytes("iso-8859-1"), "UTF-8");
System.out.println(name + "=" + value);
} else {
// 如果fileitem中封装的是上传文件
//得到文件名
String filename = item.getName();
System.out.println("filename=" + filename);
if (filename == null || filename.trim().equals("")) {
continue;
}
//处理获取到的上传文件的文件名的路径部分,只保留文件名部分
filename = filename.substring(filename.lastIndexOf("\\\\") + 1);
//获取item中的上传文件的输入流
InputStream in = item.getInputStream();
//创建缓冲区
byte buffer[] = new byte[1024];
//创建输出流对象,用于将缓冲区的数据读出到保存路径
FileOutputStream output = new FileOutputStream(savePath+ "\\\\" + filename);
//判断输入流中的数据是否已经读完
int len = 0;
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示输入流中还有数据
while ((len = in.read(buffer)) > 0) {
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\\\" + filename)当中
output.write(buffer, 0, len);
}
in.close();
output.close();
message = "success";
}
}
} catch (FileUploadException e) {
message = "failure";
e.printStackTrace();
}
out.print(message);
}