将Excel上传到Java Servlet并在上传数据时获取结果

时间:2015-03-30 18:30:01

标签: ajax excel servlets jdbc

我有一个应用程序,我尝试从浏览器上传excel文件(大约21,000行) - 该应用程序是用JSP,Servlet,Apache POI和JDBC编写的。 现在,当使用Servlet从浏览器(jsp文件)上传文件,然后使用Apache POI读取excel文件的记录,然后将行写入MySQL数据库。上传成功运行并能够将记录插入Mysql数据库。但是,jsp页面只停留在那里,只有几分钟后才会通知用户成功上传。

任何人都可以帮助我如何在浏览器上向用户显示文件已成功上传但正在处理的消息? 任何更好的代码实现也请告诉我。 我的Servlet代码如下

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.json.simple.JSONObject;

import src.com.pion.web.config.business.UploadFileProcessor;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet(name = "UploadServlet",
description = "Manages the uploaded servlet file and sends it to processing", 
urlPatterns = { "/upload.do" }
)
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = Logger.getLogger(UploadServlet.class.getName());

     private static final String UPLOAD_DIRECTORY = "upload";
        private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
        private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
        private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

    public UploadServlet() {
        super();
    }




    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //PrintWriter to send the JSON response back
        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Request does not contain upload data");
            writer.flush();
            return;
        }
        PrintWriter out = response.getWriter();

        //set content type and header attributes
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

     // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        JSONObject myObj = new JSONObject();

        String fileName = null;
        String fullName = null;
        File file = null;

        try {

            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();

            // iterates over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    file = new File(filePath);
                    fullName = item.getName().trim(); 
                    // saves the file on disk
                    item.write(file);
                }
            }           String message = null;
            UploadFileProcessor uploadProcessor = new UploadFileProcessor();
            String extension = FilenameUtils.getExtension(fullName);
            if(extenter code hereension.trim().equalsIgnoreCase("xlsx")){
                 // Send the code for processing and later insert into database
                message = uploadProces`enter code `enter code here`here`sor.processExcelFile(file);
            }

            myObj.put("success", true);
            myObj.put("message", message + " item(s) were processed for file " + fileName);
            LOGGER.info(myObj.toString());
        }
        catch(FileUploadException ex) {
            log("Error encountered while parsing the request",ex);
            myObj.put("success", false);
            LOGGER.info(myObj.toString());
        } catch(Exception ex) {
            log("Error encountered while uploading file",ex);
            myObj.put("success", false);
            LOGGER.info(myObj.toString());
        }
        out.close();
    }
}

1 个答案:

答案 0 :(得分:1)

你可以做的是,将你的操作分解为两种方法。

  1. 上传文件
  2. 读取文件并插入数据库
  3. 从客户端,使用Ajax调用servlet的文件上传方法。结果打印出一个响应代码(成功= 200 /错误= 401等)作为打印流的输出。

    如果成功(responseCode = 200),在ajax成功块中,显示警告消息,说明"上传成功,请等待..处理数据"或者"错误"。如果成功,则将另一个javascript函数调用为类似上面的ajax到servlet的数据插入方法。

    然后在上一步设置响应代码,并根据您在servlet中设置的响应代码显示警告消息。

    我将提供一个示例代码段。 (没有编译或测试。只是想引导你) 您的客户端代码应如下所示:

    function uploadFile(){
    $.ajax({
            url:"YourServlet", 
            type: "POST",
            crossDomain: true,
            dataType:"json",
            data:"type=upload&other_related_data_you_require_to_process",
            success: function(data) {
               if(data.responseCode === 200){
                  alert("file is successfully updated!! Please wait till processing the data...");
                  processData();
               }
            },
            error: function(data){
              alert("error in file Upload")
            }
      });       
    }
    function processData(){
      $.ajax({
            url:"YourServlet", 
            type: "POST",
            crossDomain: true,
            dataType:"json",
            data:"type=processData&other_related_data_you_require_to_process",
            success: function(data) {
               if(data.responseCode === 200){
                  alert("data successfully processed!! records are inserted !!");
                  processData();
               }
            },
            error: function(data){
              alert("error in file Upload")
            }
        });     
    }
    
    
    
    And your servlet code should look like:   
    
    
    
    
    
    doPost(req, res){
              String type = request.getParameter("type");
              // your "other_related_data_you_require_to_process" comes here...
    
              int reponseCode = 404;
              boolean uploadSuccess = false;
              boolean dbInsertSucess = false;
    
              if("upload").equals(type){
                 // your code to upload the file:
    
                 //if upload process is success:
                 uploadSuccess = true;
                 ...
    
                 if(uploadSuccess){
                   reponseCode = 200;
                 }
    
              }else if("processData").equals(type){
                 // your code to call database inserting process:
    
                 //if insert process is success:
                 dbInsertSucess = true;
                 ...
    
                 if(dbInsertSucess){
                   reponseCode = 200;
                 }
              }else{
                // any other type goes here.
              }
    
              // writing the  output responseCode to json / printStream:
    
              PrintWriter out = null;
              try{
                  out = res.getWriter();
                  out.println("{responseCode: "+ responseCode + "}");
                  out.flush();
                  out.close();
              }catch(Exception e){
                e.printStackTrace();
              }  
            }
    

    可以找到一篇好文章here