天天看點

檔案下載下傳 普通方式

使用servlet的方式下載下傳:

簡單的将部分核心代碼摘錄下來,如下

/**
     * 下載下傳文檔
     * @author 張國明 [email protected]
     * @version 2012-11-26 上午10:13
     */
    public void download() {
        OutputStream os = null;
        InputStream is = null;
        try {
            os = response.getOutputStream();
            is = new FileInputStream("d:/zhangm.txt");

            // 可以下載下傳任意類型的檔案
            response.setContentType("application/octet-stream");
            // 設定檔案編碼
            response.setCharacterEncoding("UTF-8");
            // 解決中文檔案名亂碼的問題
            String fileName = new String("張國明.txt".getBytes(), "iso8859-1");
            // 設定檔案以附件的方式進行下載下傳
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 以位元組的方式讀入源檔案,并将讀入的位元組輸出到目标檔案中
            byte[] tempByte = new byte[1024];
            int length = 0;
            while ((length = is.read(tempByte)) != -1) {
                os.write(tempByte, 0, length);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.getMessage();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.getMessage();
                }
            }
        }
    }      

繼續閱讀