编写上传页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="upload.do" method="post" enctype="multipart/form-data"> name:<input type="text" name="user"> 选择文件:<input type="file" name="pic"> <input type="submit" value="提交"> </form> </body> </html>
开发处理文件上传的Servlet
1、使用注解@MultipartConfig将一个Servlet标识为支持文件上传。
2、Servlet3.0将multipart/form-data的POST请求封装成Part,通过Part对上传的文件进行操作。
3.使用getSubmittedFileName方法需要tomcat8支持。
UploadServlet 代码如下:
@WebServlet(name = "UploadServlet",urlPatterns = "/upload.do") @MultipartConfig public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); String strUser = request.getParameter("user"); System.out.println(strUser); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("UTF-8"); Part part = request.getPart("pic"); out.print("文件类型为:" + part.getContentType() + "<br/>"); out.print("文件的大小为:" + part.getSize() + "<br/>"); out.print("文件信息为:" + part.getHeader("content-disposition") + "<br/>"); out.print("文件的名字为:" + part.getSubmittedFileName()); //得到服务器项目发布运行所在地址 String strFolder = request.getServletContext().getRealPath("/image")+ File.separator; File folder = new File(strFolder); if(!folder.exists()) { folder.mkdir(); } // 此处未使用UUID来生成唯一标识,用日期做为标识 String strNewFilePath = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ part.getSubmittedFileName(); String strFinalPath = strFolder + strNewFilePath; //查看文件上传路径,方便查找 System.out.println(strFinalPath); part.write(strFinalPath); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
ajax上传
<%-- Created by IntelliJ IDEA. User: ttc Date: 2018/7/13 Time: 8:47 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script> function upload() { var form = new FormData(document.getElementById("upload")); var req = new XMLHttpRequest(); req.open("post", "${pageContext.request.contextPath}/upload.do", true); req.send(form); req.onload = function () { // alert(req.responseText); document.getElementById('head').src = '${pageContext.request.contextPath}/upload/'+ req.responseText; } } </script> </head> <body> <form id="upload" action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data"> <img src="${pageContext.request.contextPath}/upload/${picpath}" id="head"> <input type="text" name="username" value="zhangsan"> <input type="file" name="file1" onchange="upload();"> <input type="submit"> </form> </body> </html>