java通过超链接和servlet配置实现服务器文件下载

  1、在页面上面我们可以简单的写成:

<td align="center"">
<a href="<c:url value="/bbsfile?filename=20150417.XLS&saveasfilename=template.xls"/>">下载导入模板</a>
</td> 

 2、在web.xml里面配置servlet向Java类的跳转:

  <servlet>
    <servlet-name>bbsfile</servlet-name>
    <servlet-class>com.zl.common.downloadfile</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>bbsfile</servlet-name>
    <url-pattern>/bbsfile</url-pattern>
  </servlet-mapping>

  3、编写下载文件的Java类:

/*
 * Created on 2004-12-22
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.zl.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.activation.FileTypeMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cd.util.ReadPropertiesFile;
import com.zl.base.core.Constants;

public class downloadfile extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public downloadfile() {
        super();
    }

    /**
     * Init method.
     * 
     * @throws ServletException
     *             never.
     */
    public void init() throws ServletException {
        return;
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        service(request, response, true);
    }

    public void service(HttpServletRequest request, HttpServletResponse response, boolean blnsyn)
            throws ServletException, IOException {
        try {
            Object user = request.getSession().getAttribute(Constants.SESSION_USER);

            if (user != null) {
                String mimeType = request.getParameter("mimeType");
                String filename = request.getParameter("filename");
                String oldfilename = request.getParameter("saveasfilename");
                if (mimeType!=null)    response.setContentType(mimeType);
                if (oldfilename == null) {
                        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                } else {
                    oldfilename = new String(oldfilename.getBytes("ISO-8859-1"),"UTF-8");;
                    response.setHeader("Content-Disposition", "attachment; filename="+ oldfilename );
                    // response.setHeader("Content-Disposition", "attachment;
                    // filename=" +oldfilename);
                }
                String uploadfilepath = ReadPropertiesFile.getInstance().getProperty("uploadfilepath", "c:/") + "announce/";
                File file = new File(uploadfilepath + filename);
                System.out.println("文件路径:"+uploadfilepath + filename);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileTypeMap fMap = FileTypeMap.getDefaultFileTypeMap();
                String filetype = fMap.getContentType(file);
                response.setContentType(filetype);
                response.setContentLength((int) file.length());
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                byte[] input = new byte[1024];
                boolean eof = false;
                while (!eof) {
                    int length = bis.read(input);
                    if (length == -1) {
                        eof = true;
                    } else {
                        bos.write(input, 0, length);
                    }
                }
                bos.flush();
                bis.close();
                bos.close();
            }
        } catch (Exception ex) {

        }
        return;
    }
    
}

  其中ReadPropertiesFile类是定义文件保存位置的方法:

package com.cd.util;

import java.io.InputStream;
import java.util.Properties;

/**
 * 读取 sale.properties文件的内容
 * 
 * @author lxk 2013-05-28 单例
 * 
 */
public class ReadPropertiesFile {
    static private ReadPropertiesFile instance = new ReadPropertiesFile(); // 唯一实例
    private Properties dbProps = null;
    
    private Properties getDbProps() {
        return dbProps;
    }
    //默认的私有的构造方法
    private ReadPropertiesFile() {
        InputStream is = ReadPropertiesFile.class.getResourceAsStream("/sale.properties");
        dbProps = new Properties();
        try {
            dbProps.load(is);
        } catch (Exception e) {
            System.err.println("不能读取属性文件. 请确保sale.properties在CLASSPATH指定的路径中");
        }
    }

    /**
     * 返回唯一实例.如果是第一次调用此方法,则创建实例
     * 
     * @return DBConnectionManager 唯一实例
     */
    public static synchronized ReadPropertiesFile getInstance() {
        if (instance == null) {
            instance = new ReadPropertiesFile();
        }
        return instance;
    }

    public String getProperty(String key, String defaultValue) {
        // 如果taglib.properties没有key,则默认defaultValue
        return instance.getDbProps().getProperty(key, defaultValue);
    }
}

  编写一个sale.properties文件,在项目里面配置服务器文件存放的路径:

##uploadfilepath=/home/webapp/sxwl_file/upload/
uploadfilepath=c:/logs/

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。