标签:servlet3-0 servlet 注解 文件上传
Servlet 3.0的另一个新特性就是提供了处理文件上传的功能,使用Servlet 3.0的内容实现文件上传需要以下几个内容:
Optional Element Summary | |
---|---|
int | fileSizeThreshold |
java.lang.String | location |
long | maxFileSize |
long | maxRequestSize |
Method Summary | |
---|---|
void | delete() |
java.lang.String | getContentType() |
java.lang.String | getHeader(java.lang.String name) |
java.util.Collection<java.lang.String> | getHeaderNames() |
java.util.Collection<java.lang.String> | getHeaders(java.lang.String name) |
java.io.InputStream | getInputStream() |
java.lang.String | getName() |
long | getSize() |
void | write(java.lang.String fileName) |
利用Servlet 3.0实现文件上传的功能,具体实现代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘index.jsp‘ starting page</title>
</head>
<body>
<form action="uploadFile" method="post" enctype="multipart/form-data">
文件描述:<input type="text" name="filetext"><br>
<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
@WebServlet(urlPatterns="/uploadFile")
@MultipartConfig(
fileSizeThreshold = 10 * 1024,//缓存大小,当上传的文件超出这个大小时会生成临时文件
location = "/temp",// 存放临时文件的目录
maxFileSize = 5 * 1024,// 单个文件大小限制
maxRequestSize = 10 * 1024// 整个请求大小限制
)
public class UploadFileServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 处理请求中文乱码
req.setCharacterEncoding("utf-8");
// 接收上传文件的描述内容
String filetext = req.getParameter("filetext");
// 接收上传文件的内容
Part part = req.getPart("upload");
// 获取上传文件的真实名称
String cd = part.getHeader("Content-Disposition");
int index = cd.indexOf("filename=\"") + 10;
String filename = cd.substring(index, cd.length() - 1);
// 读取上传目录的绝对路径
String path = getServletContext().getRealPath("/upload");
// 将上传文件进行保存
part.write(path + "/" + filename);
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
转载说明:请注明作者及原文链接,谢谢!
标签:servlet3-0 servlet 注解 文件上传
原文地址:http://blog.csdn.net/longestory/article/details/46336183