亲宝软件园·资讯

展开

java web response提供文件下载功能 java web response提供文件下载功能的实例讲解

骏马金龙 人气:0

webapp项目的结构如下图:

download.html文件的内容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <h1>资源下载:</h1>
 <p> 单纯地使用a标签时,只有浏览器不能解析的文件才会是下载,否则将被浏览器直接解析。</p>
 <a href="/WEB/resource/a.mp3" rel="external nofollow" >a.mp3</a><br>
 <a href="/WEB/resource/a.exe" rel="external nofollow" >a.exe</a><br>
 <a href="/WEB/resource/a.txt" rel="external nofollow" >a.txt</a><br>
 <a href="/WEB/resource/a.xlsx" rel="external nofollow" >a.xlsx</a><br>
 <a href="/WEB/resource/a.png" rel="external nofollow" >a.png</a><br>
 <p>因此,使用a标签结合servlet的response指示浏览器不解析这些待下载文件</p>
 <a href="/WEB/download?filename=a.mp3" rel="external nofollow" >a.mp3</a><br>
 <a href="/WEB/download?filename=a.exe" rel="external nofollow" >a.exe</a><br>
 <a href="/WEB/download?filename=a.txt" rel="external nofollow" >a.txt</a><br>
 <a href="/WEB/download?filename=a.xlsx" rel="external nofollow" >a.xlsx</a><br>
 <a href="/WEB/download?filename=a.png" rel="external nofollow" >a.png</a><br>
</body>
</html>

负责处理下载的Servlet——download.java文件的内容如下:

package com.download.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class Download
 */
public class Download extends HttpServlet {
 private static final long serialVersionUID = 1L;
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 //1.获取请求下载的文件名
 String filename = request.getParameter("filename");
 //2.获取文件的文件系统路径
 String filePath = request.getServletContext().getRealPath("resource/"+filename);
 //3.设置响应头,提示浏览器不要解析响应的文件数据,而是以附件(attachment)的形式解析,即下载功能
 response.setContentType(this.getServletContext().getMimeType(filename));
 response.setHeader("Content-Disposition", "attachment;filename="+filename);
 //4.读取文件的 输入流,以及响应的输出流,并将数据输出给客户端
 InputStream in = new FileInputStream(filePath);
 ServletOutputStream out = response.getOutputStream();
 int len = 0;
 byte[] buf = new byte[1024];
 while((len=in.read(buf))!=-1) {
  out.write(buf, 0, len);
 }
 in.close();
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 doGet(request, response);
 }
}

在浏览器地址栏中输入http://localhost:8080/DownloadServlet/download.html。

以上这篇java web response提供文件下载功能的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论