日期:2014-05-16  浏览次数:20464 次

用jsp、Servlet实现上传文件

最近项目中遇到需要导入excel文件并将文件中数据保存到数据库的问题,于是特意练习了一下文件的上传。

一、页面upload.jsp文件

<body>
  <h2>导入标准xml关系模式</h2>
  <form name="upform" action="UploadServlet" method="POST" enctype="multipart/form-data"> 
     <input type ="file" name="file1" id="file1"/><br/>
         <input type ="file" name="file2" id="file2"/><br/>  
           <input type ="file" name="file3" id="file3"/><br/> 
              <input type="submit" value="Submit" /><br/>   
               <input type="reset" />
      </form>
  </body>

二、servlet文件UploadServlet.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

 

public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { 
 File tmpDir = null;//初始化上传文件的临时存放目录   
 File saveDir = null;//初始化上传文件后的保存目录 
 public UploadServlet() {      super();    }     
 
 
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
   doPost(request,response);   
   }   
  public void init() throws ServletException {
   super.init();   
   String tmpPath = "c:\\tmpdir";   
   String savePath = "c:\\updir";   
   tmpDir = new File(tmpPath);  
   saveDir = new File(savePath); 
   if(!tmpDir.isDirectory())     
    tmpDir.mkdir();   
   if(!saveDir.isDirectory())    
    saveDir.mkdir();      
   }  
 
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
   try{   
        if(ServletFileUpload.isMultipartContent(request)){
     DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象
     dff.setRepository(tmpDir);//指定上传文件的临时目录