| servlet 和JSP的上傳下載 | |
| 具體可以看下面的例子:主要是SERVLET package oa.home.servlet; import javax.servlet.*; import oa.home.system.SysFunction;
//Initialize global variables //Process the HTTP Get request String act = SysFunction.converString(request.getParameter("act")); String endTime = null; //結束時(shí)間 Connection conn = null; DiskFileUpload diskFileUpload = new DiskFileUpload(); String strDirPath = new File(request.getSession().getServletContext().getRealPath(request.getRequestURI())).getParent(); List fileItems = null; try { //開(kāi)始上傳 //Clean up resources
下載:
JSP下載 JSP文件下載及出現getOutputStream() has already been called for this response的解決方法 http://iamin.blogdriver.com/iamin/1072546.html 一、采用RequestDispatcher的方式進(jìn)行 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";//下載文件時(shí)顯示的文件保存名稱(chēng) 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"%><% //關(guān)于文件下載時(shí)采用文件流輸出的方式處理: //加上response.reset(),并且所有的%>后面不要換行,包括最后一個(gè); //因為Application Server在處理編譯jsp時(shí)對于%>和<%之間的內容一般是原樣輸出,而且默認是PrintWriter, //而你卻要進(jìn)行流輸出:ServletOutputStream,這樣做相當于試圖在Servlet中使用兩種輸出機制, //就會(huì )發(fā)生:getOutputStream() has already been called for this response的錯誤 //詳細請見(jiàn)《More Java Pitfill》一書(shū)的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機制 270 //而且如果有換行,對于文本文件沒(méi)有什么問(wèn)題,但是對于其它格式,比如AutoCAD、Word、Excel等文件 //下載下來(lái)的文件中就會(huì )多出一些換行符0x0d和0x0a,這樣可能導致某些格式的文件無(wú)法打開(kāi),有些也可以正常打開(kāi)。 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是下載文件,而不是網(wǎng)頁(yè)或TXT.(可以彈出對話(huà)框) 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(); //注意,這里給注釋掉了,如果不注釋會(huì )出現 java.lang.IllegalStateException: getWriter() has already been called for this response 這樣的錯誤.,這是因為寫(xiě)文件流時(shí),已經(jīng)有個(gè)GETWRITER打開(kāi)了.,但在下面輸出時(shí),可以在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時(shí),就用下面這個(gè). 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; //轉換下載中文名的問(wèn)題. 注意這一行,不能放到上面filePath = bean.getUploadPath() + fileName; 這一句的上面去了.不然下載的文件名會(huì )是亂碼 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個(gè)字節,inputStream.available()為當時(shí)可讀的文件字節.因為在剛開(kāi)始時(shí)讀,所以這里實(shí)際為文件大小 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(); //這三句一定要寫(xiě).特別是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() { } } |
聯(lián)系客服