温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaWeb项目中怎么实现一个响应式下载功能

发布时间:2020-11-26 16:04:50 来源:亿速云 阅读:171 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关JavaWeb项目中怎么实现一个响应式下载功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

主要部分的代码

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

当然,现在的项目大家都使用框架,这里我使用的是(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 文件在数据库的路径
   * @param @param base 文件存放的基础路径
   * @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);
        }
        // 跳转的路径
        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!");
      }
    }
  }
}

 下来,我说一下,调用的downMb,我们都知道,在服务器上下载一个文件,

//设置响应头,控制浏览器下载该文件,形参调的是文件的长度
response.setHeader("Content-Length", String.valueOf(fileLength));
 //设置响应类型,设置输出流类型
response.setContentType("application/octet-stream;charset=utf-8"); // 改成输出excel文件

 这里我使用的是输出的Excel文件

接下来就是读文件,写文件了,相信学了java基础的都会接触IO吧,这里我就略过

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

这里使用的是缓冲流,因其使用的是浏览器打开文件的下载

下来就是写文件了,写文件也是一贯的套路,先把文件存到buff数据缓冲区,然后将buff的数据输出到浏览器供用户查看

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();

看完上述内容,你们对JavaWeb项目中怎么实现一个响应式下载功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI