Believe it,do it!

          Ideal is the beacon. Without ideal, there is no secure direction; without direction ,there is no life.
          理想是指路明燈。沒有理想,就沒有堅定的方向;沒有方向,就沒有生活。
          CTRL+T eclipse
          posts - 35, comments - 3, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          servlet 和JSP的上傳下載

          Posted on 2008-09-27 14:58 三羽 閱讀(956) 評論(0)  編輯  收藏 所屬分類: 收 藏 夾

          具體可以看下面的例子:主要是SERVLET

          package oa.home.servlet;import javax.servlet.*;
          import javax.servlet.http.*;
          import java.io.*;
          import java.util.*;
          import java.sql.*;
          import org.apache.commons.fileupload.DiskFileUpload;
          import org.apache.commons.fileupload.FileItem;
          import org.apache.commons.fileupload.FileUploadException;

          import oa.home.system.SysFunction;
          import oa.home.system.*;
          import oa.home.log.Log;
          import oa.home.basicbean.model.*;
          import oa.home.basicbean.sql.*;
          import oa.home.dbconnect.DBConnect;
          import oa.home.exception.*;

           


          public class HtfbWServlet
              extends HttpServlet {
            private static final String CONTENT_TYPE = "text/html; charset=GBK";

            //Initialize global variables
            public void init() throws ServletException {
            }

            //Process the HTTP Get request
            public void doGet(HttpServletRequest request, HttpServletResponse response) throws
                ServletException, IOException {
              response.setContentType(CONTENT_TYPE);
              PrintWriter out = response.getWriter();

              String act = SysFunction.converString(request.getParameter("act"));
              String modelName = null; //范本名稱
              int conTypeDictID = 0; //范本類型
              int specialTypeID = 0; //適應專業
              String beginTime = null; //開始時間

              String endTime = null; //結束時間
              String fileExt = null; //文件后綴名

              Connection conn = null;
              FileItem fileItem = null; //文件列
             
              FileItem fileItem1 = null; //文件列
              boolean err = false; //是否出錯
              int nownode = 0; //最后執行的代碼
              int contractModelID = 0;

              DiskFileUpload diskFileUpload = new DiskFileUpload();
              // 允許文件最大長度
              diskFileUpload.setSizeMax(100 * 1024 * 1024);
              // 設置內存緩沖大小
              diskFileUpload.setSizeThreshold(1024*1024);
              // 設置臨時目錄
              diskFileUpload.setRepositoryPath("c:/temp");

              String strDirPath = new File(request.getSession().getServletContext().getRealPath(request.getRequestURI())).getParent();
              strDirPath = strDirPath.substring(0,strDirPath.length()-2);//目錄的絕對路徑 類似D:\Documents and Settings\Administrator\jbproject/untitled10\oa
          //System.out.println("目錄的絕對路徑:" + strDirPath );

              List fileItems = null;
              try {
                fileItems = diskFileUpload.parseRequest(request);
              }
              catch (FileUploadException ex) {
                err = true;
                Log.println("fileuploadEX in HtfbWServlet :" + ex);
              }
              Iterator iter = fileItems.iterator();
              while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (fileItem.isFormField()) {
                  // 當前是一個表單項
                  if ("modelName".equals(fileItem.getFieldName()))
                    modelName = fileItem.getString();
                  if ("conTypeDictID".equals(fileItem.getFieldName()))
                    conTypeDictID = SysFunction.converInt(fileItem.getString());
                  if ("specialTypeID".equals(fileItem.getFieldName()))
                    specialTypeID = SysFunction.converInt(fileItem.getString());
                  if ("beginTime".equals(fileItem.getFieldName()))
                    beginTime = SysFunction.converString(fileItem.getString());
                  if ("endTime".equals(fileItem.getFieldName()))
                    endTime = SysFunction.converString(fileItem.getString());
                }
                else {
                  // 當前是一個上傳的文件
                  fileItem1 = fileItem; //如果是文件,則將fileItem賦給另一個fileItem1.
                  String fileName = fileItem.getName();
                  fileExt = fileName.substring(fileName.length() - 4);//文件后綴名,帶圓點"."
                }
              }
              //開始添加
              if (act.equals("add")) {
                ContractModelBean contractModel = new ContractModelBean();
                contractModel.setModelName(modelName);
                contractModel.setConTypeDictID(conTypeDictID);
                contractModel.setSpecialtyClassDictID(specialTypeID);
                contractModel.setBeginTime(beginTime);
                contractModel.setEndTime(endTime);
                contractModel.setExt(fileExt);
                contractModel.setUploadPath(strDirPath+BasicInfo.UPLOADPATH);
                contractModel.setIsEnable(0);

                try {
                  conn = DBConnect.getConnection();
                  contractModel = ContractModelHome.create(conn, contractModel);
                  contractModelID = contractModel.getID();
                }
                catch (SystemException ex1) {
                  err = true;
                  Log.println("SysEX in HtfbWServlet :" + ex1);
                }
                catch (SQLException ex1) {
                  err = true;
                  Log.println("SQLEX in HtfbWServlet :" + ex1);
                }
                if (contractModelID != 0) { //當create成功時,即contractModel不為空時,再上傳文件
                  try {

                    //開始上傳
                    String file = strDirPath+BasicInfo.UPLOADPATH + modelName +fileExt;
                    fileItem1.write(new File(file));
                  }
                  catch (Exception ex1) {
                    err = true;
                    Log.println("fileuploadEX in HtfbWServlet :" + ex1);
                  }
                  finally {
                    if (!err) {
                      nownode = 49;
                      if (conn != null) {
                        try {
                          conn.close();
                        }
                        catch (SQLException ex2) {
                          Log.error(getClass().getName() + ":updateDeptDict 不能關閉數據庫連接" +
                                    ex2);
                        }
                      }
                    }
                  }
                }
              }
              response.sendRedirect("yewu/czzhihou.jsp?nownode="+nownode+"&basicRollID="+
                                                     contractModelID);
            }
            //Process the HTTP Post request
            public void doPost(HttpServletRequest request, HttpServletResponse response) throws
                ServletException, IOException {
              doGet(request, response);
            }

            //Clean up resources
            public void destroy() {
            }
          }

           

          下載:

           

          JSP下載

          JSP文件下載及出現getOutputStream() has already been called for this response的解決方法

          http://iamin.blogdriver.com/iamin/1072546.html

          一、采用RequestDispatcher的方式進行

          1、web.xml文件中增加
            <mime-mapping>
              <extension>doc</extension>
              <mime-type>application/vnd.ms-word</mime-type>
            </mime-mapping>


          2、程序如下:

          <%@page language="java" import="java.net.*" pageEncoding="gb2312"%>
          <%
              response.setContentType("application/x-download");//設置為下載
              String filenamedownload = "/系統解決方案.doc";//即將下載的文件的相對路徑
              String filenamedisplay = "系統解決方案.doc";//下載文件時顯示的文件保存名稱
              filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
              response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
             
              try
              {
                  RequestDispatcher dispatcher = application.getRequestDispatcher(filenamedownload);
                  if(dispatcher != null)
                  {
                      dispatcher.forward(request,response);
                  }
                  response.flushBuffer();
              }
              catch(Exception e)
              {
                  e.printStackTrace();
              }
              finally
              {
             
              }
          %>


          二、采用文件流輸出的方式下載

          1、web.xml文件中增加
            <mime-mapping>
              <extension>doc</extension>
              <mime-type>application/vnd.ms-word</mime-type>
            </mime-mapping>


          2、程序如下:
          <%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%><%
              //關于文件下載時采用文件流輸出的方式處理:
              //加上response.reset(),并且所有的%>后面不要換行,包括最后一個;
              //因為Application Server在處理編譯jsp時對于%>和<%之間的內容一般是原樣輸出,而且默認是PrintWriter,
              //而你卻要進行流輸出:ServletOutputStream,這樣做相當于試圖在Servlet中使用兩種輸出機制,
              //就會發生:getOutputStream() has already been called for this response的錯誤
              //詳細請見《More Java Pitfill》一書的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機制 270
              //而且如果有換行,對于文本文件沒有什么問題,但是對于其它格式,比如AutoCAD、Word、Excel等文件
              //下載下來的文件中就會多出一些換行符0x0d和0x0a,這樣可能導致某些格式的文件無法打開,有些也可以正常打開。

              response.reset();//可以加也可以不加
              response.setContentType("application/x-download");//1、unknown ==> application/x-download
              //../../退WEB-INF/classes兩級到應用的根目錄下去
              String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "../../系統解決方案.doc";
              String filenamedisplay = "系統解決方案.doc";//系統解決方案.txt
              filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
              response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);

              OutputStream output = null;
              FileInputStream fis = null;
              try
              {
                  output  = response.getOutputStream();
                  fis = new FileInputStream(filenamedownload);

                  byte[] b = new byte[1024];
                  int i = 0;

                  while((i = fis.read(b)) > 0)
                  {
                      output.write(b, 0, i);
                  }
                  output.flush();
              }
              catch(Exception e)
              {
                  System.out.println("Error!");
                  e.printStackTrace();
              }
              finally
              {
                  if(fis != null)
                  {
                      fis.close();
                      fis = null;
                  }
                  if(output != null)
                  {
                      output.close();
                      output = null;
                  }
              }
          %>
          SERVLET下載
           
          package oa.home.basicbean.sql.viewsql;
          import javax.servlet.*;
          import javax.servlet.http.*;
          import java.io.*;
          import java.sql.*;

          import oa.home.basicbean.model.*;
          import oa.home.basicbean.sql.viewsql.*;
          import oa.home.basicbean.sql.*;
          import oa.home.dbconnect.DBConnect;
          import oa.home.log.Log;
          import oa.home.exception.*;
          import oa.home.system.*;
          public class FileDownSvt
              extends HttpServlet {
            //設置此項即告訴SERVLET下載文件,而不是網頁或TXT.(可以彈出對話框)
            private static final String CONTENT_TYPE = "APPLICATION/OCTET-STREAM";
            public void init() throws ServletException {
            }
            //Process the HTTP Get request
            public void doGet(HttpServletRequest request, HttpServletResponse response) throws
                ServletException, IOException {
              response.setContentType(CONTENT_TYPE);
          //    PrintWriter out = response.getWriter();  //注意,這里給注釋掉了,如果不注釋會出現
          java.lang.IllegalStateException: getWriter() has already been called for this response
          這樣的錯誤.,這是因為寫文件流時,已經有個GETWRITER打開了.,但在下面輸出時,可以在IF{}內用.
              //Clears any data that exists in the buffer as well as the status code and headers. If the response has been committed, this method throws an IllegalStateException.
              response.reset();
              //用IntputStream時,就用下面這個.
              ServletOutputStream outputStream = response.getOutputStream();
              InputStream inputStream = null;
              int ID = SysFunction.converInt(request.getParameter("ID"));
              ContractModelBean bean = null;
              String fileName = ""; //文件名,包括后綴名
              String filePath = ""; //文件路徑,包括文件名+后綴名
              if (ID != -1) {
                try {
                  Connection conn = DBConnect.getConnection();
                  bean = ContractModelHome.findById(conn, ID);
                }
                catch (SystemException ex) {
                  Log.println("SYSerr in FileDownSvt :" + ex);
                }
                catch (SQLException ex) {
                  Log.println("SQLerr in FileDownSvt :" + ex);
                }
                if (bean != null) {
                  fileName = bean.getModelName() + bean.getExt();
                  filePath = bean.getUploadPath() + fileName;
                  //轉換下載中文名的問題. 注意這一行,不能放到上面filePath = bean.getUploadPath() + fileName;
          這一句的上面去了.不然下載的文件名會是亂碼
                  fileName = new String(fileName.getBytes("GBK"), "ISO8859_1");
                  //設置下載的文件名與原文件名一樣.
                  response.setHeader("Content-Disposition",
                                     "attachment; filename=\"" + fileName + "\"");
                  File file = new File(filePath);
                  inputStream = new FileInputStream(file);
                  int chunk = inputStream.available(); //設每次讀CHUNK個字節,inputStream.available()為當時可讀的文件字節.因為在剛開始時讀,所以這里實際為文件大小
                  if (chunk == 0 || chunk == 1024*1024*60)
                    chunk = 1024*1024;
                  //byte數組接受文件的數據
                  byte[] buffer = new byte[chunk];
                  int length = -1;
                  try {
                    if (inputStream == null) {
                      Log.println("輸入流為空!!");
                    }
                    else {
                      while ( (length = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, length); //讀入流,保存在BYTe數組中
                      }
                    }
                    inputStream.close();
                    outputStream.flush();
                    outputStream.close(); //這三句一定要寫.特別是FLUSH(),不然文件下載不完整.
                  }
                  catch (IOException ex1) {
                    Log.println("IOerr in FileDownSvt :" + ex1);
                      PrintWriter out = response.getWriter();
                    out.println("<html>");
                    out.println("<head><title>Down</title></head>");
                    out.println("<body bgcolor=\"#ffffff\">");
                    out.println("<p> Err!!!! is not this file!!</p>");
                    out.println("</body></html>");
                  }
                }
              }
            }
            //Process the HTTP Post request
            public void doPost(HttpServletRequest request, HttpServletResponse response) throws
                ServletException, IOException {
              doGet(request, response);
            }
            //Clean up resources
            public void destroy() {
            }
          }



          ====================================================================
          import javax.servlet.*;
          import javax.servlet.http.*;

          import java.io.*;
          import java.util.*;

          public class DownLoadFileServlet extends HttpServlet 
          {
              
          public void doPost(HttpServletRequest req,HttpServletResponse res)
                  
          throws ServletException,IOException
              
          {
                  String password 
          = req.getParameter("password");
                  
          if((!checkPassword(password))||(password==null))
                  
          {
                      
          //指定內容類型,并且可顯示中文
                      res.setContentType("text/html;charset=gb2312");
                      
          //取得要在響應中輸出的文本流,即標準的html
                      PrintWriter out = res.getWriter();

                      
          //輸出頁面頭部信息
                      out.println("<head><title>下載信息</title></head>");
                      out.println(
          "<H1 align='center'>你輸入的注冊碼不正確</H1><hr>");
                  }

                  
          else
                  
          {
                      
          long totalSize = 0;
                      
          //取得要傳輸的文件,實際應用時可以將文件路徑以參數的形式傳入
                      File f = new File("D:\Program Files\Tomcat 5.0\webapps\ROOT\WEB-INF\classes\sample.pdf");
                      
          long filelength = f.length();
                      
          byte[] b = new byte[1024];

                      
          //設置文件輸出流
                      FileInputStream fin = new FileInputStream(f);
                      DataInputStream in 
          = new DataInputStream(fin);
                      
          //設置響應頭信息,讓下載的文件顯示保存信息
                      res.setHeader("Content-disposition",
                          
          "attachment;filename=" + "sample.pdf");
                      
          //設置輸出流的MIME類型
                      res.setContentType("application/pdf");
                      
          //確定長度
                      String fileSize = Long.toString(filelength);
                      
          //設置輸出文件的長度
                      res.setHeader("Content-Length",fileSize);
                      
          //取出輸出流
                      ServletOutputStream servletOut = res.getOutputStream();
                      
          //發送文件數據,每次1024字節,最后一次單獨計算
                      while(totalSize<filelength)
                      
          {
                          totalSize 
          += 1024;
                          
          if(totalSize>filelength)
                          
          {
                              
          //最后一次傳送的字節數
                              byte[] leftpart = new byte[1024-(int)(totalSize-filelength)];
                              in.readFully(leftpart);
          //讀入字節數組
                              servletOut.write(leftpart);//寫入輸出流
                          }

                          
          else
                          
          {
                              in.readFully(b);
          //讀入1024個字節到字節數組b
                              servletOut.write(b);//寫出輸出流
                          }

                      }

                      servletOut.close();
                  }

              }


              
          /*public static void main(String[] args) 
              {
                  System.out.println("Hello World!");
              }
          */


              
          //驗證注冊信息,在實際應用時可以換成到數據庫中的驗證
              private boolean checkPassword(String s)
              
          {
                  String[] passwords 
          = {"aaa","bbb","ccc","ddd","eee",
                      
          "fff","ggg","hhh","lll","mmm"}
          ;
                  
          boolean flag = false;
                  
          for (int i=0;i<passwords.length ;i++ )
                  
          {
                      
          if(s.equals(passwords[i]))
                      
          {
                          flag 
          = true;
                          
          break;
                      }

                  }

                  
          return flag;
              }


              
          public void init(ServletConfig cfg) 
                  
          throws ServletException
              
          {
                  
          super.init(cfg);
              }


              
          public void destroy()
              
          {
                  
          super.destroy();
              }

          }

          主站蜘蛛池模板: 玛多县| 富蕴县| 咸阳市| 南投县| 光山县| 益阳市| 深泽县| 团风县| 嘉黎县| 六枝特区| 呼玛县| 商丘市| 伊川县| 黔西县| 武山县| 萍乡市| 长泰县| 体育| 融水| 门源| 临潭县| 东兴市| 望城县| 稻城县| 侯马市| 香格里拉县| 巧家县| 镇赉县| 当雄县| 天津市| 虹口区| 铜川市| 即墨市| 定日县| 博客| 淳安县| 金昌市| 武乡县| 金溪县| 资中县| 东海县|