Servlet3.0新增了request.getParts()/getPart(String filename) api,用于获取使用multipart/form-data格式传递的http请求的请求体,通常用于获取上传文件。
//使用@WebServlet配置UploadServlet的访问路径
@WebServlet(name = "UploadFile", urlPatterns = "/UploadFile.adub")
//使用注解@MultipartConfig将一个Servlet标识为支持文件上传
@MultipartConfig(maxFileSize = 8388608) //8M
public class UploadFile extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String number = request.getParameter("number");
//存储路径
String savePath = request.getServletContext().getRealPath("/upload");
//Servlet3.0将multipart/form-data的POST请求封装成Part,通过Part对上传的文件进行操作。
//Part part = parts[0];//从上传的文件集合中获取Part对象
Part part = request.getPart("file");//通过表单file控件()的名字直接获取Part对象
String msg = "", status = "1", fullname = "";
//Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
//获取请求头,请求头的格式:form-data; name="file"; filename="snmp4j--api.zip"
String header = part.getHeader("content-disposition");
if (header.lastIndexOf(".") == -1) {
msg = "未上传文件!";
} else {
//得到上传文件的后缀名
String str = header.substring(header.lastIndexOf("."), header.length() - 1);
//把文件写到指定路径
try {
part.write(savePath + File.separator + number + str);
msg = "上传成功!";
//文件相对路径+文件名
fullname = "/upload/" + number + str;
} catch (Exception e) {
e.printStackTrace();
msg = "上传失败";
status = "0";
}
}
PrintWriter out = response.getWriter();
out.println(
"<script>parent.callback('" + msg + "','" + status + "','" + fullname + "')</script>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}