【servlet3.0新特性】文件上传改进API 实例

在Servlet 3.0 中不需要导入任何第三方jar包,并且提供了很方便进行文件上传的功能;

原本文件上传时通过 common-fileupload或者SmartUpload,上传比较麻烦.

下面说明一下servlet3.0上传文件注意事项:

1. html中 <input type="file">表示文件上传控件;

2. form的 enctype="multipart/form-data";

3.在Servlet类前加上 @MultipartConfig

4.request.getPart()获得;

下面给出servlet3.0上传文件的实例代码:

fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form method="post" enctype="multipart/form-data" action="upload">
		<input type="file" id="file" name="file" /> 
		<input type="text" id="name" name="name" /> 
		<input type="submit" value="提交" />
	</form>
</body>
</html>

UploadServlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class UploadServlet extends HttpServlet {
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Part part = request.getPart("file");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<body>");
		out.println("此文件的大小:" + part.getSize() + "<br />");
		out.println("此文件类型:" + part.getContentType() + "<br />");
		out.println("文本框内容:" + request.getParameter("name") + "<br />");
		out.println(UploadUtil.getFileName(part) + "<br />");
		out.println("</body>");
		out.println("</html>");
	}
}

启动tomcat7.0输入URL:http://localhost:8080/Servlet3/upload 执行结果如下图:

【servlet3.0新特性】文件上传改进API 实例.png

下面附带【servlet3.0新特性】专题文件所有代码

【servlet3.0新特性】全部代码下载地址

来源:csdn//作者:admin/更新时间:2013-11-15
相关文章
评论:
验证码:
匿名评论: