首页 > 代码库 > java 上传1(使用java组件fileupload)

java 上传1(使用java组件fileupload)

使用fileupload要添加以下包

 

例子1

后台程序

    @RequestMapping(value="http://www.mamicode.com/demo1")
    public String demo1(HttpServletRequest request,HttpServletResponse response){
        
        return "/demo1";
    }
    
    @RequestMapping(value="http://www.mamicode.com/demo1U",method=RequestMethod.POST)
    public String demo1U(HttpServletRequest request,HttpServletResponse response) throws FileUploadException{
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。
        if (isMultipart == true) {
           FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
           ServletFileUpload upload = new ServletFileUpload(factory);
           List<FileItem> items = upload.parseRequest(request);
           Iterator<FileItem> itr = items.iterator();
           while (itr.hasNext()) {
               FileItem item = (FileItem) itr.next();
               //检查当前项目是普通表单项目还是上传文件。
               if (item.isFormField()) {//如果是普通表单项目,显示表单内容。
                   String fieldName = item.getFieldName();
                   if (fieldName.equals("name")) //对应demo1.html中type="text" name="name"
                   System.out.print("the field name is" + item.getString());//显示表单内容。
               }
               
               else {//如果是上传文件,显示文件名。
                   System.out.print("the upload file name is" + item.getName());
               }
           }
        } else {
            System.out.print("the enctype must be multipart/form-data");
        }      
        return null;
    }

 

前台jsp

 

<%@ 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="http://www.mamicode.com/">
    <title>demo1</title>
  </head>
 
  <body>
       //必须是multipart的表单数据。
    <form name="myform" action="<%=basePath%>/upload/demo1U" method="post" enctype="multipart/form-data">
       Your name: <br>
       <input type="text" name="name" size="15"><br>
       File:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="http://www.mamicode.com/Commit">
    </form> <br>
  </body>
</html>

 

 


 

 

例子2

后台程序

    @RequestMapping(value="http://www.mamicode.com/demo2")
    public String demo2(HttpServletRequest request,HttpServletResponse response){
        
        return "/demo2";
    }
    
    @RequestMapping(value="http://www.mamicode.com/demo2U",method=RequestMethod.POST)
    public String demo2U(HttpServletRequest request,HttpServletResponse response) throws FileUploadException{
    
        String uploadPath="D:\\temp";
          boolean isMultipart = ServletFileUpload.isMultipartContent(request);
          if(isMultipart==true){
              try{
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(request);//得到所有的文件
               Iterator<FileItem> itr = items.iterator();
                while(itr.hasNext()){//依次处理每个文件
                 FileItem item=(FileItem)itr.next();
                 String fileName=item.getName();//获得文件名,包括路径
                 if(fileName!=null){
                     File fullFile=new File(item.getName());
                     File savedFile=new File(uploadPath,fullFile.getName());
                     item.write(savedFile);
                 }
                }
                System.out.print("upload succeed");
              }
              catch(Exception e){
                 e.printStackTrace();
              }
          }
          else{
              System.out.println("the enctype must be multipart/form-data");
          }
        
        
        return null;
    }

前台jsp

<%@ 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="http://www.mamicode.com/">
    
    <title>demo2</title>
  </head>
 
  <body>
    <form name="myform" action="<%=basePath%>/upload/demo2U" method="post" enctype="multipart/form-data">
       File1:<br>
       <input type="file" name="myfile"><br>
       File2:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="http://www.mamicode.com/Commit">
    </form>
  </body>
</html>

 

 


 

 

例子3

 

后台程序

    @RequestMapping(value="http://www.mamicode.com/demo3")
    public String demo3(HttpServletRequest request,HttpServletResponse response){
        
        return "/demo3";
    }
    
    
    @RequestMapping(value="http://www.mamicode.com/demo3U",method=RequestMethod.POST)
    public String demo3U(HttpServletRequest request,HttpServletResponse response) throws FileUploadException{
    
        File uploadPath = new File("D:\\temp");//上传文件目录
        if (!uploadPath.exists()) {
           uploadPath.mkdirs();
        }
        // 临时文件目录
        File tempPathFile = new File("d:\\temp\\buffer\\");
        if (!tempPathFile.exists()) {
           tempPathFile.mkdirs();
        }
        try {
           DiskFileItemFactory factory = new DiskFileItemFactory();
           factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
           factory.setRepository(tempPathFile);//设置缓冲区目
           ServletFileUpload upload = new ServletFileUpload(factory);    
           upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
     
           List<FileItem> items = upload.parseRequest(request);//得到所有的文件
           Iterator<FileItem> i = items.iterator();
           while (i.hasNext()) {
               FileItem fi = (FileItem) i.next();           
               String fileName = fi.getName();
               if (fileName != null) {
           File fullFile = new File(fi.getName());
           File savedFile = new File(uploadPath, fullFile
                  .getName());
           fi.write(savedFile);
               }
           }
           System.out.print("upload succeed");
        } catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }

前台jsp

<%@ 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="http://www.mamicode.com/">
    
    <title>demo3</title>
      </head>
 
  <body>
       //必须是multipart的表单数据。
    <form name="myform" action="<%=basePath%>/upload/complete" method="post" enctype="multipart/form-data">
       File:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="http://www.mamicode.com/Commit">
    </form>
  </body>
</html>

 

 


 

 

 

例子4 通用的例子(待以后修改)

 

后台程序

    @RequestMapping(value="http://www.mamicode.com/complete",method=RequestMethod.POST)
    public String complete(HttpServletRequest request,HttpServletResponse response) throws FileUploadException{
    
        File uploadPath = new File("D:\\temp");//上传文件目录
        if (!uploadPath.exists()) {
           uploadPath.mkdirs();
        }
        // 临时文件目录
        File tempPathFile = new File("d:\\temp\\buffer\\");
        if (!tempPathFile.exists()) {
           tempPathFile.mkdirs();
        }
        try {
           DiskFileItemFactory factory = new DiskFileItemFactory();
           factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
           factory.setRepository(tempPathFile);//设置缓冲区目
           ServletFileUpload upload = new ServletFileUpload(factory);    
           upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
     
           List<FileItem> items = upload.parseRequest(request);//得到所有的文件
           Iterator<FileItem> i = items.iterator();
           while (i.hasNext()) {
               FileItem fi = (FileItem) i.next();
               if(fi.isFormField()){//如果是普通的表单字段
                   
               }else{//如果是上传文件,显示文件名。
                   String fileName = fi.getName();
                   if (fileName != null) {                     
                       //检查文件后缀格式  
                   String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();  
                   
                   List<String> extList=new ArrayList<String>();
                   extList.add("sql");
                   extList.add("txt");
                     if(extList.contains(fileEnd)){
                         File fullFile = new File(fi.getName());
                         File savedFile = new File(uploadPath, fullFile.getName());
                         fi.write(savedFile);
                     }else{
                         System.out.print("ext error");
                     }               
                   }
               }           
           }
           System.out.print("upload succeed");
        } catch (Exception e) {
           e.printStackTrace();
        }
        return null;
    }

 

java 上传1(使用java组件fileupload)