zoukankan      html  css  js  c++  java
  • Servlet实现图片文件上传

    1.首先要导入以下两个jar包:

    commons-fileupload-1.2.1.jar
    commons-io-1.4.jar

    2.jsp文件:index.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9     <head>
    10         <base href="<%=basePath%>">
    11 
    12         <title>文件上传</title>
    13         <meta http-equiv="pragma" content="no-cache">
    14         <meta http-equiv="cache-control" content="no-cache">
    15         <meta http-equiv="expires" content="0">
    16         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17         <meta http-equiv="description" content="This is my page">
    18         <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21     </head>
    22 
    23     <body>
    24         表单/带文件
    25         <br>
    26         <!--    application/x-www-form-urlencoded只有字符串的表单 -->
    27         <form action="${pageContext.request.contextPath}/UploadPictureServlet" method="post" enctype="multipart/form-data">
    28 
    29             文件名
    30             <input type="text" name="filename">
    31             <br />
    32             文件
    33             <input type="file" name="file">
    34             <br />
    35             <input type="submit" value="提交">
    36         </form>
    37     </body>
    38 </html>

    3.Servlet文件:

      package com.pearl.util;

    1 import java.io.File; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.util.List; 5 import java.util.UUID; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.apache.commons.fileupload.FileItem; 13 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 14 import org.apache.commons.fileupload.servlet.ServletFileUpload; 15 16 public class UploadPictureServlet extends HttpServlet { 17 18 public void destroy() { 19 super.destroy(); 20 } 21 22 public void doGet(HttpServletRequest request, HttpServletResponse response) 23 throws ServletException, IOException { 24 doPost(request, response); 25 } 26 27 public void doPost(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 30 try { 31 // ① 创建ServletFileUpload实例 32 DiskFileItemFactory factory = new DiskFileItemFactory(); 33 34 String realPath = getServletContext().getRealPath("/"); 35 // // 【设置缓存目录】 36 factory.setRepository(new File(realPath)); 37 ServletFileUpload upload = new ServletFileUpload(factory); 38 // ② 创建DiskFileItemFactory 39 // ③ 解析request获取List<FileItem> 40 // 【表单大小总和】 41 upload.setSizeMax(1024 * 1024 * 60); 42 // 【单个文件不得超过】 43 upload.setFileSizeMax(1024 * 1024 * 20); 44 // 【处理中文乱码】 45 upload.setHeaderEncoding("UTF-8"); 46 if (upload.isMultipartContent(request)) {// 判断是否为带文件表单 <form 47 // enctype="multipart/form-data" 48 List<FileItem> list = upload.parseRequest(request); 49 for (FileItem item : list) { 50 // 文本或文件 51 if (item.isFormField()) { 52 // 文本字段 53 // 获取变量名 54 String key = item.getFieldName();// 表单字段的变量名 55 String value = item.getString("UTF-8");// 表单字段的输入值 56 System.out.println(key); 57 System.out.println(value); 58 } else { 59 // 文件 60 // 文件类型 61 // text/plain .txt 62 // image/png .png 63 // image/bmp .bmp 64 String contentType = item.getContentType(); 65 // 文件名 66 String fileName = item.getName();// 表单的输入框值 67 // 变量名 68 String name = item.getFieldName();// 表单的变量名 69 // 文件 内容 70 String content = item.getString(); 71 // 二进制文件 72 InputStream input = item.getInputStream(); 73 System.out.println(contentType); 74 System.out.println(fileName); 75 System.out.println(name); 76 //System.out.println(content); 77 System.out.println(input); 78 79 // ① 服务端目录 (服务端真实路径) 80 String dir = getServletContext().getRealPath("/upload"); 81 System.out.println(dir); 82 // ② 文件名冲突 83 if (fileName.contains("/")) { 84 fileName = fileName.substring(name.lastIndexOf("/") + 1); 85 System.out.println(fileName); 86 } 87 // (添加前缀 唯一字符串, 时间毫秒值 UUID随机产生全球唯的id) 88 String path = UUID.randomUUID().toString() + "#" + fileName; 89 90 // ③ 写入File对象 91 File driSave = new File(dir); 92 if (!driSave.exists()) { 93 driSave.mkdir(); 94 } 95 File saveFile = new File(dir, path); 96 97 if (!saveFile.exists()) { 98 saveFile.createNewFile(); 99 } 100 System.out.println(saveFile.getAbsolutePath()); 101 item.write(saveFile); 102 // 删除临时文件 103 item.delete(); 104 input.close(); 105 } 106 107 } 108 } else { 109 System.out.println("表单不存在文件"); 110 } 111 // ④ 循环显示内容FileItem 112 } catch (Exception e) { 113 // TODO Auto-generated catch block 114 e.printStackTrace(); 115 } 116 } 117 118 public void init() throws ServletException { 119 120 } 121 122 }

    4.web.xml文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app version="2.5" 
     3     xmlns="http://java.sun.com/xml/ns/javaee" 
     4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
     6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     7  
     8   <servlet>
     9     <description>This is the description of my J2EE component</description>
    10     <display-name>This is the display name of my J2EE component</display-name>
    11     <servlet-name>UploadPictureServlet</servlet-name>
    12     <servlet-class>com.pearl.util.UploadPictureServlet</servlet-class>
    13   </servlet>
    14 
    15   <servlet-mapping>
    16     <servlet-name>UploadPictureServlet</servlet-name>
    17     <url-pattern>/UploadPictureServlet</url-pattern>
    18   </servlet-mapping>
    19   <welcome-file-list>
    20     <welcome-file>index.jsp</welcome-file>
    21   </welcome-file-list>
    22 </web-app>

    5.完成

  • 相关阅读:
    python学习第十一天 -- 函数式编程
    python学习第十天 -- 函数
    python学习第九天 -- 列表生产式
    python学习第八天 -- 迭代
    (转载)C# 编程 使用可空类型
    Func的介绍——c#封装的代理
    select SCOPE_IDENTITY()用法
    insert into 语句的三种写法
    面试感悟----一名3年工作经验的程序员应该具备的技能
    SQL中常用模糊查询的四种匹配模式&&正则表达式
  • 原文地址:https://www.cnblogs.com/yeqrblog/p/4894181.html
Copyright © 2011-2022 走看看