星生

导航

文件上传file upload

使用fileupload组件实现文件上传:

 

导入

commons-fileupload-1.2.2.jar

commons-io-2.1.jar

 

官方文档:

// Check that we have a file upload request 检测是否有文件上传的请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
/**************************************************************/
// Create a factory for disk-based file items 创建一个基于磁盘文件项目的工厂
DiskFileItemFactory factory = new DiskFileItemFactory();

// Configure a repository 配置存储库(to ensure a secure temp location is used 确保一个安全的临时位置被利用)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request
List<FileItem> items = upload.parseRequest(request);

/******************************************************************************/
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Set factory constraints 设置工厂约束
factory.setSizeThreshold(yourMaxMemorySize); //
factory.setRepository(yourTempDirectory); //

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint 设置整体请求大小的约束
upload.setSizeMax(yourMaxRequestSize);

// Parse the request
List<FileItem> items = upload.parseRequest(request);

/***********************************************************************/
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = iter.next();

    if (item.isFormField()) {
        processFormField(item);
    } else {
        processUploadedFile(item);
    }
}
/*****************************************************************************/
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = iter.next();

    if (item.isFormField()) {
        processFormField(item);
    } else {
        processUploadedFile(item);
    }
}
/*********************************************************/




 1 package com.servlet;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 import java.util.List;
 9 
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 import org.apache.commons.fileupload.FileItem;
16 import org.apache.commons.fileupload.FileUploadException;
17 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
18 import org.apache.commons.fileupload.servlet.ServletFileUpload;
19 
20 public class FileUploadServlet extends HttpServlet {
21     private static final long serialVersionUID = 1L;
22        
23     public FileUploadServlet() {
24         super();
25     }
26 
27     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
28         // TODO Auto-generated method stub
29     }
30 
31     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
32             
33         
34         boolean isMultipart = ServletFileUpload.isMultipartContent(request);
35         System.out.println("是否有文件上传:"+isMultipart);
36         
37         DiskFileItemFactory factory = new DiskFileItemFactory();
38         
39         factory.setSizeThreshold(1024*512);  // 设置内存缓冲区的阀值512k
40         //设置临时存储文件的目录
41         File tempDir = new File("E:\\upload");
42         factory.setRepository(tempDir);
43         
44         ServletFileUpload upload = new ServletFileUpload(factory);
45         upload.setSizeMax(1024*1024*5);  //设置上传文件的最大值 5M
46         try {
47             //解析上传文件流,获取FileItem的对象列表
48             List<FileItem> items = upload.parseRequest(request);
49             
50             for(FileItem item :items){
51                 if(item.isFormField()){
52                     String name = item.getName();
53                     String value = item.getString();
54                     System.out.println(name+":"+value);
55                 }else{//如果是文件域则将文件保存到d:\\file
56                     String fieldName = item.getFieldName();
57                     String fileName = item.getName();
58                     String contentType = item.getContentType();
59                     long sizeInBytes = item.getSize();
60                     
61                     System.out.println("fieldName:"+fieldName);
62                     System.out.println("fileName:"+fileName);
63                     System.out.println("contentType:"+contentType);
64                     System.out.println("sizeInBytes:"+sizeInBytes);
65                     
66                     
67                     InputStream is = item.getInputStream();
68                     byte [] buffer = new byte[1024];
69                     int len = 0;
70                     fileName = "E:\\file\\"+fileName;
71                     OutputStream out = new FileOutputStream(fileName);
72                     while ((len = is.read(buffer))!=-1){
73                         out.write(buffer,0,len);
74                     }
75                     out.close();is.close();
76                     
77                 }
78             }
79         } catch (FileUploadException e) {
80             e.printStackTrace();
81         }    
82             
83     }
84 
85 }
View Code
1 <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
2         file:<input type="file" name="file"/>
3         <input type="submit" value="Submit"/>
4</form>

 







 

posted on 2014-11-29 13:24  Q星ZX  阅读(418)  评论(0编辑  收藏  举报