档案上传与一般表单提交的格式不同。
一般表单提交默认enctype = "application/x-www-form-urlencoded"
档案上传则必须设置enctype = "multipart/form-data"
动手做做看
在main资料夹下,新建一个文件上传页面uploadFile.jsp
<% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><body> <h1>文件上传</h1> <form action="<%=basePath%>FileSvl" enctype = "multipart/form-data" method = "post"> 文件名:<input type="text" name="fname" id="fname"> <input type="file" name="file" onchange="show(this)"><br> <input type="submit" value="上传"> ${msg} </form></body><script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.min.js"></script><script type="text/javascript"> function show(source){ var arrs = $(source).val().splite('\\'); var filename = arrs[arrs.length - 1]; $(#fname).val(filename); }</script>
注:js脚本用来显示被选择的文件名称。
新建一个FileSvl
import javax.servlet.http.Part;@WebServlet("/FileSvl")@MultipartConfig(maxFileSize = 300 * 1024)public class FileSvl extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/main/uploadFile.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fname = request.getParameter("fname"); try { Part part = request.getPart("file"); String picPath = request.getServletContext().getRealPath("/") + "pic"; part.write(picPath + "/" + fname); request.setAttribute("msg","上传成功"); }catch(Exception e) { e.printStackTrace(); request.setAttribute("msg", e.getMessage()); } request.getRequestDispatcher("/main/uploadFile.jsp").forward(request, response); }}
注:用@MultipartConfig标籤可限制上传档案大小
使用request.getPart()取得上传档案后储存在变数里,再转存到指定路径的资料夹内。