一下代码运行没有问题,但下载保存后的文件有残缺,帮我看看吧:<%
   //源文件名
   String filename = "aa.jpg";
   //源文件存放路径
   String filePath = "d:\\jiaoan\\uploads\\";
   
   // 设置响应头和下载保存的文件名
   response.setContentType("APPLICATION/OCTET-STREAM");
   response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
   
   // 打开指定文件的流信息
   java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filePath + filename);   
   // 写出流信息
   int i;
   while ((i=fileInputStream.read()) != -1) {
     out.write(i);
   }
   
   //关闭文件
   fileInputStream.close();
   out.close();
   
%>

解决方案 »

  1.   

    在jsp中out的类型是JspWriter,此类继承于java.io.Writer,主要用来输出字符流.
    你可用以下语句尝试一下,看看能否解决问题
         FileInputStream fis = new FileInputStream(filePath + filename);
    OutputStream outs = response.getOutputStream();
    byte[] buf = new byte[4*1024];
    int bytesRead;
    while ((bytesRead = fis.read(buf)) != -1) {
    outs.write(buf,0,bytesRead);
    }
      

  2.   

    try {
    File ff = new File(filePath + File.separatorChar + fName);

    byte[] buffer;
    int length = (new Long(ff.length())).intValue();
    buffer = new byte[1024]; iin = new BufferedInputStream(new java.io.FileInputStream(ff));
    //设置类型和头信息
    response.setContentType("application/octet-stream");
    response.setHeader(
    "Content-Disposition",
    "attachment;filename=" + TranCodeBean.tranCodeC(fRealName));
    int len = iin.read(buffer, 0, buffer.length);


    dout = new BufferedOutputStream(response.getOutputStream());
    while (len != -1) {
    dout.write(buffer, 0, len);
    len = iin.read(buffer, 0, buffer.length);
    } } catch (Exception e) {
    e.printStackTrace();

    } finally {
    iin.close();
    dout.flush();
    dout.close();
    }
      

  3.   

    根据大家的提示我调试好了,正确的如下:谢谢WYJ123((Q&Q))给出正确的思路//设置响应头和下载保存的文件名
      response.setHeader("Content-Type", "application/force-download;");
      response.setHeader("Content-disposition","attachment; filename=" + filename + "");
      //打开指定文件的流信息
      java.io.BufferedInputStream bis = null;
      java.io.BufferedOutputStream bos = null;
      try {
            bis = new java.io.BufferedInputStream(new java.io.FileInputStream(filepath + filename));
            bos = new java.io.BufferedOutputStream(response.getOutputStream());        byte[] buff = new byte[10*1024];
            int bytesRead;
            //写出流信息
            while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
               bos.write(buff,0,bytesRead);
            }
      }catch(final java.io.IOException e) {
            //失败显示错误信息
    System.out.println ( "文件下载出错! " + e );
      }finally{
            //完成后关闭输入/输出流
    if (bis != null) bis.close();
            if (bos != null) bos.close();
    }