欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaWeb响应下载功能实例代码(包含工具类)

程序员文章站 2023-11-17 10:16:58
今天通过本文给大家分享是关于javaweb的响应(response)下载 以下是我的demo: 页面我就粘主要部分的代码

今天通过本文给大家分享是关于javaweb的响应(response)下载

以下是我的demo:

页面我就粘主要部分的代码

<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响应下载实例代码(包含工具类),希望对大家有所帮助