Servlet上传文件详细解析以及注意事项

开发 后端
本文主要介绍了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

责任编辑:林师授 来源: 博客园
相关推荐

2011-06-29 09:56:29

QT UI 动态加载

2010-02-03 10:21:46

初学Python

2009-10-21 17:32:30

综合布线注意事项

2017-04-06 09:49:55

Hive注意事项优化

2012-04-10 09:53:15

2014-05-16 10:04:19

JavaScriptthis原理

2009-12-03 20:21:21

PHP文件上传

2011-07-21 14:28:17

MySQL事务事务保存点

2021-09-28 08:59:40

UPS蓄电池电源

2010-01-26 16:54:58

学习C++

2011-07-01 14:33:19

网站优化

2011-05-26 11:22:04

SEO

2009-12-15 17:47:17

VSIP

2011-07-21 15:20:31

iPhone SDK 多线程

2011-07-22 17:35:17

java路径

2011-03-22 08:56:30

2011-09-01 09:45:01

Ubuntu上安装Mo

2010-06-13 09:52:24

UML依赖

2010-11-25 13:53:13

UI设计移动

2009-12-30 10:12:30

MPLS VPN
点赞
收藏

51CTO技术栈公众号