servlet3.0获取参数与文件上传代码示例
转:
servlet3.0获取参数与文件上传代码示例
-
package com.igeek.servlet;
-
-
import java.io.IOException;
-
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.apache.catalina.core.ApplicationPart;
-
-
/**
-
* Servlet implementation class AddUserServlet
-
*/
-
@WebServlet("/addUser")
-
@MultipartConfig // 该servlet要接收文件上传
-
public class AddUserServlet extends HttpServlet {
-
private static final long serialVersionUID = 1L;
-
-
/**
-
* @see HttpServlet#HttpServlet()
-
*/
-
public AddUserServlet() {
-
super();
-
// TODO Auto-generated constructor stub
-
}
-
-
/**
-
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
-
*/
-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
//普通请求参数获取
-
String uname = request.getParameter("uname");
-
String upass = request.getParameter("upass");
-
System.out.println("uname="+uname+";upass="+upass);
-
//获取文件
-
Collection<Part> parts = request.getParts();
-
//遍历取出文件
-
for (Part part : parts) {
-
System.out.println("-----------------------");
-
if(part.getHeader("Content-Disposition").contains("filename")){
-
String fileName = part.getHeader("Content-Disposition");
-
fileName = fileName.substring(fileName.indexOf("filename=\"")+10, fileName.lastIndexOf("\""));
-
String name = request.getParameter("head");
-
System.out.println(name);
-
//存储文件 利用part的api将临时文件写入目标文件
-
part.write("d:/"+fileName);
-
}
-
System.out.println("-----------------------");
-
}
-
}
-
-
/**
-
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
-
*/
-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
// TODO Auto-generated method stub
-
doGet(request, response);
-
}
-
-
}