Commons-FileUpload組件

1、表單設置


JSP<form action="/uploadservlet" method="post" enctype="multipart/form-data">

2、Servlet文件上傳:doPost

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (!item.isFormField()) {
                        String fileName = item.getName();
                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/uploads");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }

3、Servlet文件下載:

 public void doGet(HttpServletRequest request,HttpServletResponse response){

         String aFilePath = null;    //要下載的文件路徑
         String aFileName = null;    //要下載的文件名
         FileInputStream in = null;  //輸入流
         ServletOutputStream out = null;  //輸出流

         try
         {
          
             aFilePath = getFilePath(request); 
             aFileName = getFileName(request);

             response.setContentType(getContentType(aFileName) + "; charset=UTF-8");
             response.setHeader("Content-disposition", "attachment; filename=" + aFileName);

             in = new  FileInputStream(aFilePath + aFileName); //讀入文件
            out = response.getOutputStream();
            out.flush();
            int aRead = 0;
            while((aRead = in.read()) != -1 & in != null)
            {
             out.write(aRead);
            }
            out.flush();
      }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章