首页 > 代码库 > 【JavaEE企业应用实战学习记录】servlet3.0上传文件

【JavaEE企业应用实战学习记录】servlet3.0上传文件

 1 <%-- 2   Created by IntelliJ IDEA. 3   User: Administrator 4   Date: 2016/10/6 5   Time: 14:20 6   To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <html>10 <head>11     <title>upload</title>12 </head>13 <body>14 <form method="post" action="/upload" enctype="multipart/form-data">15     文件名:<input type="text" id="name" name="name"><br/>16     选择文件:<input type="file" id="file" name="file"><br/>17     <input type="submit" value="http://www.mamicode.com/上传">18 </form>19 </body>20 </html>
 1 package sanglp.servlet; 2  3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.MultipartConfig; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.Part;10 import java.io.IOException;11 import java.io.PrintWriter;12 import java.util.Collection;13 14 /**15  * Created by Administrator on 2016/10/6.16  */17 @WebServlet(name = "upload",urlPatterns = {"/upload"})18 @MultipartConfig19 public class UploadServlet extends HttpServlet {20     @Override21     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {22         //super.service(req, resp);23         resp.setContentType("text/html;charset=GBK");24         PrintWriter out=resp.getWriter();25         //获取普通请求参数26         String fileName=req.getParameter("name");27         //获取上传文件的上传域28         Part part=req.getPart("file");29         out.println("上传文件的类型为"+part.getContentType()+"<br/>");30         out.println("上传文件的大小为"+part.getSize()+"<br/>");31         //获取文件上传的Header Name32         Collection<String> headerNames=part.getHeaderNames();33         for(String headerName:headerNames){34             out.println(headerName+"-->"+part.getHeader(headerName)+"<br/>");35         }36         //将上传的文件写入服务器37         part.write(getServletContext().getRealPath("/uploadFiles")+"/"+fileName);38     }39 }

技术分享

【JavaEE企业应用实战学习记录】servlet3.0上传文件