JavaWeb項目中怎么實現(xiàn)一個響應式下載功能

今天就跟大家聊聊有關(guān)JavaWeb項目中怎么實現(xiàn)一個響應式下載功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

在寶豐等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供成都網(wǎng)站制作、成都網(wǎng)站設(shè)計 網(wǎng)站設(shè)計制作專業(yè)公司,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計,營銷型網(wǎng)站,外貿(mào)營銷網(wǎng)站建設(shè),寶豐網(wǎng)站建設(shè)費用合理。

主要部分的代碼

<a href = "${pageContext.request.contextPath }/user/courseTab">模板下載</a>

當然,現(xiàn)在的項目大家都使用框架,這里我使用的是(SSM),好了,粘代碼

@Controller
@RequestMapping("/user")
public class UploadController {
@RequestMapping(value="/courseTab",method=RequestMethod.GET)
  public void courseTab(HttpServletResponse response,HttpServletRequest request) throws IOException{
    String path = request.getSession().getServletContext().getRealPath("/courseTab/課表上傳模板.xls");
    DownUtil.downMb(response, path, "課表模板"+DateFormat.formatSimple(new Date()));
}
}

 這里我使用的DownUtil工具類是我自己寫的,下來我粘到文章中

package org.cxxy.base.cxsc.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
/**
 * @Title: DownUtil.java
 * @Package org.cxxy.base.cxsc.util
 * @Description:文件下載工具類
 * @author ChoviWu
 * @date 2017年6月18日 下午2:44:17
 * @version V1.0
 */
public class DownUtil {
  /**
   *
   * @Description:
   * @param @param response
   * @param @param url 文件在數(shù)據(jù)庫的路徑
   * @param @param base 文件存放的基礎(chǔ)路徑
   * @param @param folderPath 上傳所在的文件夾
   * @param @return
   * @param @throws IOException
   * @return int
   * @throws
   */
  @SuppressWarnings("unused")
  public static int downFile(HttpServletResponse response, String url,
      Integer down, String base, String folderPath) throws IOException {
    // 文件的名稱
    String fileName = url.split("/")[1];
    System.out.println(fileName);
    // 文件的后綴
    String last = url.substring(url.lastIndexOf(".") + 1);
    System.out.println(last);
    // 文件路徑
    String downFilePath = base + folderPath + fileName;
    Long fileLength = new File(downFilePath).length();// 文件的長度
    if (fileLength != 0) {
      response.reset();
      response.setContentType("application/octet-stream;charset=utf-8"); // 改成輸出excel文件
      try {
        response.setHeader(
            "Content-disposition",
            "attachment; filename="
                + new String(fileName.getBytes("utf-8"),
                    "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;
      FileInputStream fis = null;
      try {
        fis = new FileInputStream(downFilePath);
        bis = new BufferedInputStream(fis);
        // 輸出流
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesread;
        // 寫文件
        while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
          bos.write(buff, 0, bytesread);
        }
        // 跳轉(zhuǎn)的路徑
        fis.close();
        bis.close();
        bos.close();
      } catch (FileNotFoundException e) {
        System.out.println("File is Not Exsist!");
      }
    } else {
      // 拋異常
      response.getWriter()
          .write("<script charset='utf-8' type='text/javascript'>alert('該資源不存在!');history.go(-1);</script>");
      return down;
    }
    down++;
    return down;
  }
  /**
   *
   * @Description: 下載的模板
   * @param @param response
   * @param @param path 路徑名
   * @param @param name 模板名稱
   * @param @throws IOException
   * @return void
   * @throws
   */
  @SuppressWarnings("unused")
  public static void downMb(HttpServletResponse response, String path,
      String name) throws IOException {
    Long fileLength = new File(path).length();// 文件的長度
    System.out.println("文件的長度:" + fileLength);
    if (fileLength != 0) {
      response.reset();
      response.setContentType("application/octet-stream;charset=utf-8"); // 改成輸出excel文件
      try {
        response.setHeader(
            "Content-disposition",
            "attachment; filename="
                + new String(name.getBytes("utf-8"),
                    "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;
      FileInputStream fis = null;
      try {
        fis = new FileInputStream(path);
        bis = new BufferedInputStream(fis);
        // 輸出流
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesread;
        // 寫文件
        while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
          bos.write(buff, 0, bytesread);
        }
        fis.close();
        bis.close();
        bos.close();
      } catch (FileNotFoundException e) {
        System.out.println("File is Not Exsist!");
      }
    }
  }
}

 下來,我說一下,調(diào)用的downMb,我們都知道,在服務器上下載一個文件,

//設(shè)置響應頭,控制瀏覽器下載該文件,形參調(diào)的是文件的長度
response.setHeader("Content-Length", String.valueOf(fileLength));
 //設(shè)置響應類型,設(shè)置輸出流類型
response.setContentType("application/octet-stream;charset=utf-8"); // 改成輸出excel文件

 這里我使用的是輸出的Excel文件

接下來就是讀文件,寫文件了,相信學了java基礎(chǔ)的都會接觸IO吧,這里我就略過

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

這里使用的是緩沖流,因其使用的是瀏覽器打開文件的下載

下來就是寫文件了,寫文件也是一貫的套路,先把文件存到buff數(shù)據(jù)緩沖區(qū),然后將buff的數(shù)據(jù)輸出到瀏覽器供用戶查看

byte[] buff = new byte[2048];
  int bytesread;
  // 寫文件
  while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesread);
  }

當讀寫完文件之后,千萬別忘了要關(guān)閉文件流(當然,關(guān)閉流的順序也不能變)

fis.close();
bis.close();
bos.close();

看完上述內(nèi)容,你們對JavaWeb項目中怎么實現(xiàn)一個響應式下載功能有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

本文標題:JavaWeb項目中怎么實現(xiàn)一個響應式下載功能
網(wǎng)頁URL:http://muchs.cn/article24/gphgje.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護、建站公司微信小程序、網(wǎng)站制作自適應網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名