zoukankan      html  css  js  c++  java
  • Servlet上传文件详细解析以及注意事项

    准备阶段,下载需要的包:

    在Servlet中进行文件上传需要用到外部的类库,apache提供了这些类库, 主要需要commons-fileupload.jar和commons-io.jar

    下载的步骤如下:

    进入www.apache.org网站, ——>在Projects下找到commons,点击进入——>找到Components下的FileUpload,点击进入就可以找到下载

    页面如下:

    可以看到这里有开发指南和下载地址,如果要详细学习,慢慢看这里的资源就可以了。

    commons-io.jar包的下载地址:http://commons.apache.org/fileupload/dependencies.html

    把两个jar包放到WEB-INF的lib目录下。

    开发阶段:

    上传页面: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.         <form action="upload" method="post" enctype="multipart/form-data">  
    25.             文件别名:<input type="text" name="filename"><br>  
    26.             选择文件:<input type="file" name="fileupload"><br>  
    27.             <input type="submit" value="提交">  
    28.           
    29.         </form>  
    30.    </body>  
    31.  </html> 

    这里注意第24行,上传文件时要指定提交方法method="post", 信息类型为enctype="multipart/form-data"

    上传功能servlet:FileUpload

    1. package com.sunflower.servlet;  
    2.    
    3.  import java.io.File;  
    4.  import java.io.IOException;  
    5.  import java.util.Iterator;  
    6.  import java.util.List;  
    7.    
    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.FileItemFactory;  
    15.  import org.apache.commons.fileupload.FileUploadException;  
    16.  import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
    17.  import org.apache.commons.fileupload.servlet.ServletFileUpload;  
    18.    
    19.  public class FileUpload extends HttpServlet {  
    20.      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
    21.          req.setCharacterEncoding("UTF-8");  
    22.          fileControl(req, resp);  
    23.      }  
    24.    
    25.      /**  
    26.       * 上传文件的处理  
    27.       */ 
    28.      private void fileControl(HttpServletRequest req, HttpServletResponse resp) throws ServletException {  
    29.    
    30.          // 在解析请求之前先判断请求类型是否为文件上传类型  
    31.          boolean isMultipart = ServletFileUpload.isMultipartContent(req);  
    32.    
    33.          // 文件上传处理工厂  
    34.          FileItemFactory factory = new DiskFileItemFactory();  
    35.    
    36.          // 创建文件上传处理器  
    37.          ServletFileUpload upload = new ServletFileUpload(factory);  
    38.    
    39.          // 开始解析请求信息  
    40.          List items = null;  
    41.          try {  
    42.              items = upload.parseRequest(req);  
    43.          }  
    44.          catch (FileUploadException e) {  
    45.              e.printStackTrace();  
    46.          }  
    47.    
    48.          // 对所有请求信息进行判断  
    49.          Iterator iter = items.iterator();  
    50.          while (iter.hasNext()) {  
    51.              FileItem item = (FileItem) iter.next();  
    52.              // 信息为普通的格式  
    53.              if (item.isFormField()) {  
    54.                  String fieldName = item.getFieldName();  
    55.                  String value = item.getString();  
    56.                  req.setAttribute(fieldName, value);  
    57.              }  
    58.              // 信息为文件格式  
    59.              else {  
    60.                  String fileName = item.getName();  
    61.                  int index = fileName.lastIndexOf("\\");  
    62.                  fileName = fileName.substring(index + 1);  
    63.                  req.setAttribute("realFileName", fileName);  
    64.    
    65.                  // 将文件写入  
    66.  //                String path = req.getContextPath();  
    67.  //                String directory = "uploadFile";  
    68.  //                String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/" + directory;  
    69.                  String basePath = req.getRealPath("/uploadFile");  
    70.                  File file = new File(basePath, fileName);  
    71.                  try {  
    72.                      item.write(file);  
    73.                  }  
    74.                  catch (Exception e) {  
    75.                      e.printStackTrace();  
    76.                  }  
    77.              }  
    78.          }  
    79.    
    80.          try {  
    81.              req.getRequestDispatcher("/uploadsuccess.jsp").forward(req, resp);  
    82.          }  
    83.          catch (IOException e) {  
    84.              e.printStackTrace();  
    85.          }  
    86.      }  
    87.  } 

    这里要注意第66~68行,将文件上传到Web项目的"uploadFile"文件夹中,如果用这种方法得到的路径是"http://localhost:8080/upload/uploadFile", 而创建File类用的路径是绝对路径,这样就会出问题,所以这里要用的是得到真实路径的方法HttpServletRequest.getRealPath().

    以上是最简单的文件上传,如果要加入上传的限制可以在DiskFileItemFactory和ServletFileUpload中进行限制:

    在34行后加入:

    1. //创建临时文件目录  
    2.         File tempFile = new File(req.getRealPath("/temp"));  
    3.         //设置缓存大小  
    4.         ((DiskFileItemFactory) factory).setSizeThreshold(1024*1024);  
    5.         //设置临时文件存放地点  
    6.         ((DiskFileItemFactory) factory).setRepository(tempFile); 

    注意第72行的FileItem.write()方法,如果使用了这个方法写入文件,那么临时文件会被系统自动删除.

    在38行后加入:

    1. //将页面请求传递信息最大值设置为50M  
    2. upload.setSizeMax(1024*1024*50);  
    3. //将单个上传文件信息最大值设置为6M  
    4. upload.setFileSizeMax(1024*1024*6); 

    原文链接:http://www.cnblogs.com/hanyuan/archive/2012/06/09/upload.html

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    从程序员到项目经理
    wumii 爆款总结经验
    快速的搭建JFinal的ORM框架示例
    Hibernate all-delete-orphan[转]
    HHvm Apache 2.4 Nginx建站环境搭建方法安装运行WordPress博客
    雷军是如何从程序员蜕变成职业经理人的
    Postgresql数据库数据简单的导入导出
    如何一年看50本好书?
    清除DNS解析缓存
    mysql 下 计算 两点 经纬度 之间的距离
  • 原文地址:https://www.cnblogs.com/shipeng22022/p/4614099.html
Copyright © 2011-2022 走看看