Explain the response download method of Java Web
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 href = "${pageContext.request.contextPath }/user/courseTab">模板下载</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='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!"); } } } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



South Korean court sentenced three people to prison for cryptocurrency scams. South Korea's Busan District Court recently made a verdict on a complicated cryptocurrency fraud case, and the three main culprits were sentenced to jail for fraudulent investors of 110 million won (about 416,000 US dollars). The court found that the three people used the fake "exclusive trading algorithm" as bait and promised a huge monthly return of 30% to defraud many victims. This algorithm does not actually exist, it is a tool used to commit fraud. The three defendants (published by last names only: Kim, Lee and Joe) used the public's enthusiasm for cryptocurrencies to fabricate lies from a global trading network to attract investors. The main culprit Jin was sentenced to four and a half years in prison, while Li and Qiao were sentenced to three and a half years in prison respectively. The judge pointed out that their behavior was severe

This article summarizes the information of the top ten virtual currency trading apps including Binance, Ouyi and Sesame Open Door, but for security reasons, the URL is not provided directly. Instead, it emphasizes the importance of safe access to the official platform through trusted channels and provides verification methods. At the same time, the article reminds investors to consider factors such as security, transaction fees, currency selection when choosing an APP, and pay attention to the risks of virtual currency trading.

The charity party hosted by the Langley Community Health and Hospital Foundation raised $331,000 to establish the Guru Nanak Endowment Fund. The donation raised by the "Heart of Giving" charity party for Langley Memorial Hospital has reached one-third of its million-dollar target. On April 4, more than 250 guests attended the annual fundraising event at the Cloverdale Mirage Ballroom. Activities include raffle draws, silent auctions, live auctions and fundraising games, with 50/50 draws continuing until May 2. Since 2019, the Heart of Giving charity party has brought together donors every year to celebrate the community and raise donations, said Heather Scott, executive director of the Langley Community Health and Hospital Foundation. She said: "Testimation

The crypto market is changing with opportunities and risks coexisting, and every cryptocurrency is facing tremendous pressure. This article will analyze the current situation of three cryptocurrencies: Sui, Ethereum and BlockDag, and explore the reasons and future trends behind their price fluctuations. Sui: Price is under pressure, and the future trend is unknown. Sui's price trend shows a classic head and shoulder reversal pattern. The current price hovers around US$2.22, down 8.73% from the neckline of US$2.52. In the past 24 hours, nearly US$1.92 million long positions have been closed, and shorts have dominated. Although the MACD indicator bent slightly upward, the volume was insufficient, with support at $2.16 and $1.42 respectively. Unless the bulls break through the $2.52 resistance level, S

Binance, OKX, Coinbase, Kraken, Huobi, Gate.io, Gemini, XBIT, Bitget and MEXC are all strictly selected platforms for regulatory selection. 1. Binance adapts to supervision by setting up a compliance sub-platform. 2. OKX strengthens compliance management through KYB verification. 3.Coinbase is known for its compliance and user-friendliness. 4.Kraken provides powerful KYC and anti-money laundering measures. 5. Huobi operates in compliance with the Asian market. 6.Gate.io focuses on transaction security and compliance. 7. Gemini focuses on security and transparency. 8.XBIT is a model of decentralized transaction compliance. 9.Bitget continues to work in compliance operations. 10.MEXC passed

The top ten cryptocurrency exchanges in 2025 are: 1. Binance, 2.Bybit, 3.OKX, 4.Coinbase, 5.Kraken, 6.HTX, 7.Gate.io, 8.KuCoin, 9.Crypto.com, 10.BitMEX. These exchanges have their own characteristics to meet the needs of different users.

The cryptocurrency market rebounded strongly, and the trends of major digital assets were differentiated. The surge in Binance Coin (BNB) prices have attracted market attention, while Ethereum (ETH) price analysis shows it faces resistance. Against this backdrop, BlockDag (BDAG) stands out among the top cryptocurrencies in 2025, with BDAG adoption soaring after the release of Keynote3. Its easy-to-use X1 mining machine application has attracted more than 1 million users, sold 19.1 billion tokens, raising $212.5 million, marking a major leap in the process of inclusive cryptocurrency. BNB price rose, trading at about $627.99, with a market value of $89.47 billion, up 1.81% in recent times, consistent with the market trend. Since its launch in 2017

The top ten leading virtual currency trading apps in the world in 2025 are: 1. Binance, 2. Gate.io, 3. OKX, 4. Huobi Global, 5. Bybit, 6. Kraken, 7. FTX, 8. KuCoin, 9. Coinbase, 10. Crypto.com.
