<form action="/upload" method="post" enctype="multipart/form-data"> 用户:<input type="text" name="username"> <br> 文件:<input type="file" name="imgFile"> <br> <input type="submit" value="上传"> </form> |
<servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>test.mylo.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping> [size=12.0000pt] |
public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 获取文件上传的目录路径 String path = request.getSession().getServletContext().getRealPath("/upload/"); //2. 获取日期 String date = new SimpleDateFormat("yyyy-MM-dd ").format(new Date()); //3. 创建目录对象 File file = new File(path+date); if (!file.exists()){ file.mkdirs(); } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // 把请求数据转换为FileItem对象 List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } // 遍历 for(FileItem item : items){ //判断 if(item.isFormField()){ // 普通表单元素如:<input type="text"/> System.out.println("获取输入用户:" + item.getString("UTF-8")); }else{ // 文件域:<input type="file" /> // 获取文件名 String fileName = item.getName(); // 获取后缀 String last = fileName.substring(fileName.lastIndexOf(".")); // 处理文件名唯一 String uniqueFileName = UUID.randomUUID().toString().replaceAll("-","") + last; // 文件上传 try { item.write(new File(file,uniqueFileName)); } catch (Exception e) { e.printStackTrace(); } // 删除临时文件 item.delete(); } } } } [size=12.0000pt] |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |