• JSP之文件上传


    摘要:本文介绍怎么结合servlet,jsp来完成文件的上传

    1,需要引入两个jar包

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

    2,修改web.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app version="3.0" 
     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_3_0.xsd">
     7   <display-name></display-name>    
     8   
     9   
    10   <servlet>
    11       <servlet-name>upload</servlet-name>
    12       <servlet-class>UploadServlet</servlet-class>
    13   <init-param>
    14     <param-name>filePath</param-name>
    15       <param-value>store</param-value>
    16   </init-param>
    17   <init-param>
    18     <param-name>tempFilePath</param-name>
    19       <param-value>temp</param-value>
    20   </init-param>
    21   </servlet>
    22   <servlet-mapping>
    23   
    24   <servlet-name>upload</servlet-name>
    25   <url-pattern>/upload</url-pattern>
    26   </servlet-mapping>
    27   <welcome-file-list>
    28     <welcome-file>index.jsp</welcome-file>
    29   </welcome-file-list>
    30 </web-app>

    3,需要一个html界面来点击上传的文件路径等

     1 <html>
     2 <head>
     3 <title>Upload</title>
     4 </head>
     5 <body >
     6   <form name="uploadForm" method="POST"
     7     enctype="MULTIPART/FORM-DATA"
     8     action="upload">
     9     <table>
    10       <tr>
    11        <td><div align="right">User Name:</div></td>
    12        <td><input type="text" name="username" size="30"/> </td>
    13       </tr>
    14       <tr>
    15        <td><div align="right">Upload File1:</div></td>
    16        <td><input type="file" name="file1" size="30"/> </td>
    17       </tr>
    18       <tr>
    19         <td><div align="right">Upload File2:</div></td>
    20         <td><input type="file" name="file2" size="30"/> </td>
    21       </tr>
    22       <tr>
    23         <td><input type="submit" name="submit" value="upload"></td>
    24         <td><input type="reset" name="reset" value="reset"></td>
    25       </tr>
    26     </table>
    27   </form>
    28 </body>
    29 </html>

     

    4,通过servlet来控制文件的上传

     1 import java.io.File;
     2 import java.io.IOException;
     3 import java.io.PrintWriter;
     4 import java.util.Iterator;
     5 import java.util.List;
     6 
     7 import javax.servlet.ServletConfig;
     8 import javax.servlet.ServletException;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 import org.apache.commons.fileupload.FileItem;
    14 import org.apache.commons.fileupload.FileUploadException;
    15 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    16 import org.apache.commons.fileupload.servlet.ServletFileUpload;
    17 
    18 
    19 public class UploadServlet extends HttpServlet{
    20     private String filePath;//存放上传文件的目录
    21     private String tempFilePath;//存放临时文件的目录
    22     @Override
    23     protected void doPost(HttpServletRequest req, HttpServletResponse res)
    24             throws ServletException, IOException {
    25         res.setContentType("text/plain");
    26         //向客户端发送响应正文
    27         PrintWriter outNet=res.getWriter();
    28         //创建一个基于硬盘的FileItem工厂
    29         DiskFileItemFactory factory=new DiskFileItemFactory();
    30         //设置向硬盘写数据时所用的缓冲区的大小,此处为4k
    31         factory.setSizeThreshold(4*1024);
    32         //设置临时目录
    33         factory.setRepository(new File(tempFilePath));
    34         //设置一个文件上传处理器
    35         ServletFileUpload upload=new ServletFileUpload(factory);
    36         //设置允许上传的文件的最大尺寸,此为4m
    37         upload.setFileSizeMax(4*1024*1024);
    38         try {
    39             List items=upload.parseRequest(req);
    40             Iterator ite=items.iterator();
    41             while (ite.hasNext()) {
    42                 FileItem item=(FileItem) ite.next();
    43                 if(item.isFormField()){
    44                      processFormField(item,outNet); //处理普通的表单域
    45                     
    46                 }else{
    47                     processUploadedFile(item,outNet); //处理上传文件
    48                     
    49                 }
    50             }
    51             outNet.close();
    52             
    53         } catch (FileUploadException e) {
    54             throw new RuntimeException();
    55         }
    56     }
    57 
    58     private void processUploadedFile(FileItem item, PrintWriter outNet) {
    59         String filename=item.getFieldName();
    60         int index=filename.lastIndexOf("\");
    61         filename=filename.substring(index+1,filename.length());
    62         long filesize=item.getSize();
    63         
    64         if(filename.equals("")&&filesize==0)return;
    65             
    66         File uploadFile=new File(filePath+"/"+filename); 
    67         
    68         try {
    69             item.write(uploadFile);
    70             outNet.print(filename+"is saved.");
    71             outNet.print("The size of"+filename+"is"+filesize+"
    ");
    72         } catch (Exception e) {
    73             throw new RuntimeException();
    74         }
    75         
    76     }
    77 
    78     private void processFormField(FileItem item, PrintWriter outNet) {
    79         String name=item.getFieldName();
    80         String value=item.getString();
    81         outNet.println(name+":"+value+"
    ");
    82         
    83     }
    84 
    85     @Override
    86     public void init(ServletConfig config) throws ServletException {
    87         
    88         super.init(config);
    89         filePath=config.getInitParameter("filePath");
    90         tempFilePath=config.getInitParameter("tempFilePath");
    91         filePath=getServletContext().getRealPath("/")+"store";
    92         tempFilePath=getServletContext().getRealPath("/")+"temp";
    93     }
    94 }
  • 相关阅读:
    Vue(小案例_vue+axios仿手机app)_go实现退回上一个路由
    nyoj 635 Oh, my goddess
    nyoj 587 blockhouses
    nyoj 483 Nightmare
    nyoj 592 spiral grid
    nyoj 927 The partial sum problem
    nyoj 523 亡命逃窜
    nyoj 929 密码宝盒
    nyoj 999 师傅又被妖怪抓走了
    nyoj 293 Sticks
  • 原文地址:https://www.cnblogs.com/ztyy04126/p/4969065.html
Copyright © 2020-2023  润新知