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 三羽 阅读(949) 评论(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();
    }

}


只有注册用户登录后才能发表评论。


网站导航: