java上传文件

需要两个jar包

commons-fileupload-1.2.2.jar与commons-io-2.4.jar

表单格式必须为

<form action="fileupload.jsp" method="post" enctype="multipart/form-data">

一个接受文件的例子

<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘fileupload.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <%
        request.setCharacterEncoding("utf-8");
        String uploadpath="d:/upload";
        //File folder=new File("upload");
        DiskFileItemFactory factory= new DiskFileItemFactory();
        factory.setSizeThreshold(30*1024);
        factory.setRepository(factory.getRepository());
        ServletFileUpload upload=new ServletFileUpload(factory);
        int maxsize=5*1024*1024;
        List list=upload.parseRequest(request);
        Iterator iterator=list.iterator();
        while(iterator.hasNext()){
            FileItem item=(FileItem)iterator.next();
            if(!item.isFormField()){
                String filePath=item.getName();
                if(filePath!=null){
                    File filename=new File(item.getName()); 
                }
                if(item.getSize()>maxsize){
                    out.print("文件太大 ,不得超过5M");
                    break;
                }
                File saveFile=new File(uploadpath,filePath);
                item.write(saveFile);
                out.print("文件上传成功 ");
                
            }
            response.sendRedirect("success.jsp");
            
        }
        
     %>
  </body>
</html>

 禁止上传指定类型文件:

<%@page import="org.apache.commons.io.filefilter.SuffixFileFilter"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘fileupload.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <%
        request.setCharacterEncoding("utf-8");
        String uploadpath="d:/upload";
        //File folder=new File("upload");
        DiskFileItemFactory factory= new DiskFileItemFactory();
        factory.setSizeThreshold(30*1024);
        factory.setRepository(factory.getRepository());
        ServletFileUpload upload=new ServletFileUpload(factory);
        int maxsize=5*1024*1024;
        List list=upload.parseRequest(request);
        
        String[] limit = new String[]{".exe", "dat"};
        SuffixFileFilter filter = new SuffixFileFilter(limit);
        
        Iterator iterator=list.iterator();
        while(iterator.hasNext()){
            FileItem item=(FileItem)iterator.next();
            if(!item.isFormField()){
                String filePath=item.getName();
                if(filePath!=null){
                    File filename=new File(item.getName()); 
                }
                if(item.getSize()>maxsize){
                    out.print("文件太大 ,不得超过5M");
                    break;
                }
                File saveFile=new File(uploadpath,filePath);
                boolean flag = filter.accept(saveFile);
                if(flag){
                    out.print("error");
                    break;
                }else{
                    item.write(saveFile);
                    out.print("文件上传成功 ");
                };
                
            }
            response.sendRedirect("success.jsp");
            
        }
        
     %>
  </body>
</html>

 


 

对于form表单的属性enctype,通常使用默认值application/x-www-form-urlencoded,这样可以通过request对象的getParameter()方法获取表单元素值,但是在文件域中将表单的enctype属性设置成了multipart/form-data,这样通过getParameter()方法就无法获取了。

下面介绍一个实例

上传页面

<%
          Date now = new Date();
          String time = String.format("%tF", now);
       %>
    <form action="fileupload.jsp" method="post" enctype="multipart/form-data">
        选择文档<input type="file" name="file1" size="20">
        上传者<input type="text" name="name" size="20">
        文档名称<input type="text" name="filenames" size="20">
        上传时间<input type="text" name="upTime" value="<%=time %>">
        <input type="submit" value="提交"/>
    </form>

处理页面

<%
        String name=null, filenames=null, upTime=null,meg=null;
        request.setCharacterEncoding("utf-8");
        String uploadpath = "d:/upload";
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(30*1024);
        factory.setRepository(factory.getRepository());
        ServletFileUpload upload = new ServletFileUpload(factory);
        int maxsize = 5*1024*1024;
        List list = upload.parseRequest(request);
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            FileItem item = (FileItem) iterator.next();
            if(!item.isFormField()){
                String filePath = item.getName();
                if(filePath!=null){
                    File filename = new File(item.getName());
                }
                if(item.getSize()>maxsize){
                    meg="too big";
                    break;
                }
                File saveFile = new File(uploadpath, filePath);
                item.write(saveFile);
                meg="success";
            }else{
                String formName = item.getFieldName();
                String formcon = item.getString("utf-8");
                if(formName.equals("name")){
                    name = formcon;
                }    
                else if(formName.equals("filenames")){
                    filenames = formcon;
                }
                else if(formName.equals("upTime")){
                    upTime = formcon;
                }
            }
        }    
        request.setAttribute("meg", meg);
        request.setAttribute("name", name);
        request.setAttribute("filenames", filenames);
        request.setAttribute("uptime", upTime);
        request.getRequestDispatcher("success.jsp").forward(request, response);
     %>

成功页面

<body>
        ${requestScope.meg }
        ${requestScope.name }
        ${requestScope.filenames }
        ${requestScope.uptime }
  </body>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。