搜索
首页Javajava教程有关讲解Java Web的响应下载方法

有关讲解Java Web的响应下载方法

Jul 22, 2017 pm 02:24 PM
javawebweb工具

纸上得来终觉浅,绝知此事要躬行!今天博主分享是关于javaweb的响应(response)下载

以下是我的Demo:

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

67cd8d1652231f66d323b1db71360b5e模板下载5db79b134e9f6b82c0b36e0489ee08ed

 

当然,现在的项目大家都使用框架,这里我使用的是(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=&#39;utf-8&#39; type=&#39;text/javascript&#39;>alert(&#39;该资源不存在!&#39;);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();

 

以上是有关讲解Java Web的响应下载方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前By尊渡假赌尊渡假赌尊渡假赌
威尔R.E.P.O.有交叉游戏吗?
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器