java通過超連結和servlet配置實現伺服器檔案下載

來源:互聯網
上載者:User

標籤:

  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/

 

java通過超連結和servlet配置實現伺服器檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.