Template download Of course, everyone uses frameworks in current projects. Here I use (SSM). Okay, paste the code."/> Template download Of course, everyone uses frameworks in current projects. Here I use (SSM). Okay, paste the code.">
search
HomeJavajavaTutorialExplain the response download method of Java Web

Explain the response download method of Java Web

Jul 22, 2017 pm 02:24 PM
javawebwebtool

What you see on paper is ultimately shallow, but you know you have to do it! Today the blogger shared about javaweb response (response) download

The following is my Demo:

I will stick to the main part of the page Code

<a>模板下载</a>

Of course, everyone uses frameworks in current projects, here I use (SSM) , ok, paste the code

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

The DownUtil tool class I use here is written by myself, I will paste it into the article

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!");

			}
		}
	}
}

Come on, let me talk about it. We all know that downMb is called to download a file on the server.

//Set the response header, controls the browser to download the file, the formal parameter adjusts the length of the file

response.setHeader("Content-Length", String.valueOf(fileLength));

//Set the response type, set the output stream type

response.setContentType("application/octet-stream;charset=utf-8"); // 改成输出excel文件

Here I am using the output Excel file

The next step is to read the file and write the file. I believe I have learned java. The basics will come into contact with IO. I will skip it here

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

The buffer stream is used here because it uses the browser to open the file for download

The next step is to write files. Writing files is also a consistent routine. First, save the file to the buff data buffer, and then output the buff data to the browser for the user to view

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

After reading and writing the file, don’t forget to close the file stream (of course, the order of closing the stream It cannot be changed)

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

The above is the detailed content of Explain the response download method of Java Web. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools