JSP文件下载完美解决方案

本例子是在eclipse+myeclipse+tomcat测试成功的,中文乱码问题也得到了很好的解决

,本实例是基于jsp+servlet实现的。

如有问题,请发邮件:txyhl@126.com

由于不能上传附件,现将源码贴出来,供大家参考。

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the fileDowload</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>DownloadFile</servlet-name>
    <servlet-class>test.DownloadFile</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>DownloadFile</servlet-name>
    <url-pattern>/servlet/DownloadFile</url-pattern>
  </servlet-mapping>
</web-app>

 

download.jsp

<%@ page contentType="text/html;charset=GB2312" %>
<html>
 <head>
  <title>下载测试</title>
 </head>
 <body>
  <center>
  <!--当然,要先在c:/upload文件夹下面放上aa.pdf文件,以供测试,以后会写出来上传程序供大家参考-->
   <a href="servlet/DownloadFile?path=c:/upload/&filename=aa.pdf">下载文件</a>
  </center>
 </body>
</html>

DownloadFile.java

package test;

 

/**
 * 编写人:于红磊
 * 功能:实现了文件的下载
 * 时间:2006年10月3日
 */
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

public class DownloadFile extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    /**
     * Constructor of the object.
     */
    public DownloadFile() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        javax.servlet.ServletOutputStream out = response.getOutputStream();

        String filepath=new String(request.getParameter("path").getBytes("ISO8859_1"),"GB2312").toString();
        String filename=new String(request.getParameter("filename").getBytes("ISO8859_1"),"GB2312").toString();
        System.out.println("DownloadFile filepath:" + filepath);
        System.out.println("DownloadFile filename:" + filename);
        java.io.File file = new java.io.File(filepath + filename);
        if (!file.exists()) {
         System.out.println(file.getAbsolutePath() + " 文件不存在!");
            return;
        }
        // 读取文件流
        // 读取文件流
        java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file);
            // 下载文件
            // 设置响应头和下载保存的文件名
            if (filename != null && filename.length() > 0) {
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=/"" + new String(filename.getBytes("gb2312"),"iso8859-1") + "/"");
                if (fileInputStream != null) {
                    int filelen = fileInputStream.available();
                    //文件太大时内存不能一次读出,要循环
                    byte[] buf = new byte[1024];
                    int n = 0;
                    while (n != -1)
                    {
                      n = fileInputStream.read(buf);
                      if(n>0) out.write(buf, 0, n);
                    }
                }
                fileInputStream.close();
                out.close();
            }
        }
    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass().getName());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException
     *             if an error occure
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

完成,有什么问题希望大家提出来,我会继续改进的。

 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值