0

我想使用 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");
    }

}
}

请告诉我如何解决我的问题以及如何上传这个文件是用户定义的目录意味着(D://菜单)文件夹thanx是Advance

4

0 回答 0