如何使用浏览器在servlet中上传excel表

时间:2013-09-13 07:58:40

标签: java excel jsp servlets

我想使用servlet API在我的本地系统上传我的Excel工作表,但我得到了异常

java.io.FileNotFoundException:D:\ Core-Java_Eclipse.metadata.plugins
\ org.eclipse.wst.server.core \ tmp0 \ wtpwebapps \ UploadMenu \ uploaded(访问被拒绝)

这里我使用两个jar 1. commons-fileupload-1.2.1.jar 2. commons-io-1.4.jar 我不想使用第三方实施jar

请参阅我在servlet中编写的代码

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
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.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


 public class UploadServlet extends HttpServlet {


  protected void service(HttpServletRequest request, HttpServletResponse 
  response)        throws ServletException, IOException {
    String ctxPath=request.getRealPath("/");
    File dir=new File(ctxPath,"uploaded");
    if(!dir.exists()){
        dir.mkdir();
    }
    Writer out=response.getWriter();
    boolean uploadData=ServletFileUpload.isMultipartContent(request);
    if(uploadData){
        DiskFileItemFactory factory=new DiskFileItemFactory();
        factory.setSizeThreshold(1024*1024*10);
        factory.setRepository(new File("c:\\temp"));
        ServletFileUpload upload=new ServletFileUpload(factory);
        upload.setSizeMax(1024*1024*50);
        try{
            List<FileItem> fileItems=upload.parseRequest(request);
            Iterator<FileItem> i=fileItems.iterator();
            while(i.hasNext()){
                FileItem fi=i.next();
                if(!fi.isFormField()){
                    String fieldName=fi.getFieldName();
                    String fileName=fi.getName();
                    String contentType=fi.getContentType();
                    boolean isInMemory=fi.isInMemory();
                    long sizeInByte=fi.getSize();
                    StringTokenizer tok=new 
                              StringTokenizer(fileName,"/");
                    String fileToWrite="";
                    while(tok.hasMoreTokens()){
                         fileToWrite=tok.nextToken();
                    }
                    File file=new File(dir,fileToWrite);
                    fi.write(file);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
         out.write("<h1>File Uploaded in <br/>"+dir.getAbsolutePath());
    }else{
        out.write("No File Uploaded");
    }

}
}

请告诉我如何解决我的问题以及如何上传此文件是用户 define directry表示(D:// menu)文件夹 thanx是Advance

0 个答案:

没有答案