jsp中文件下载的实现

方式一:采用RequestDispatcher进行

package cn.jbit.download.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 6765085208899952414L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String filedownload = "/upload/helloworld.jar";//即将下载的文件的相对路径
		String filedisplay = "helloworld.jar";//下载文件时显示的文件保存名称
		response.setContentType("application/x-download");//设置为下载application/x-download
		//response.setContentType("application/x-msdownload");//设置为下载application/x-msdownload
		//response.setContentType("application/octet-stream");//设置为下载application/octet-stream
		response.addHeader("Content-Disposition", "attachment;filename="
				+ filedisplay);
		
		try {
			RequestDispatcher rd = request.getRequestDispatcher(filedownload);
			if(rd != null)
			{
				rd.forward(request,response);
			}
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
方式二:采用文件流输出的方式下载

package cn.jbit.download.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadOfIOServlet extends HttpServlet {

	private static final long serialVersionUID = 6765085208899952414L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String basePath = request.getSession().getServletContext().getRealPath("/upload");
		//System.out.println(basePath);
		String filedisplay = "helloworld.jar";
		String filedownload = basePath + File.separator + "helloworld.jar";
		System.out.println("----------------------"+filedownload);
		response.setContentType("applicaiton/x-download");
		response.addHeader("Content-Disposition", "attachment;filename="+filedisplay);
		
		InputStream is = null;
		OutputStream os = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		
		is = new FileInputStream(new File(filedownload));
		bis = new BufferedInputStream(is);
		os = response.getOutputStream();
		bos = new BufferedOutputStream(os);
		
		byte[] b = new byte[1024];
		int len = 0;
		while((len = bis.read(b)) != -1){
			bos.write(b,0,len);
		}
		
		bis.close();
		is.close();
		bos.close();
		os.close();
	}
}
方式三:网页上做超级链接(不推荐使用,样服务器上的目录资源会直接暴露给最终用户)

<a href="/DownloadFile/upload/helloworld.jar">helloworld.jar</a>
jsp页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'download.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  
  <body>
  	下载1<a href="/DownloadFile/upload/helloworld.jar">helloworld.jar</a><br/>
  	下载2<a href="/DownloadFile/servlet/downloadServlet">helloworld.jar</a><br/>
  	下载3<a href="/DownloadFile/servlet/downloadOfIOServlet">helloworld.jar</a><br/>
  	下载4<a href="/DownloadFile/download/filedownload.action">helloworld.jar</a><br/>
  </body>
</html>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用JSP实现本地文件下载,可以按照以下步骤进行操作: 1. 在JSP页面上,创建一个下载链接或按钮,用于触发文件下载操作。例如: ```html <a href="download.jsp?filename=filename.txt">Download File</a> ``` 2. 创建一个名为download.jspJSP页面,用于处理文件下载请求。在该页面,可以使用以下代码来实现文件下载: ```jsp <% String filename = request.getParameter("filename"); String filePath = "path/to/files/" + filename; // 指定文件的路径 File file = new File(filePath); if (file.exists()) { response.setContentType("application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); try (InputStream inputStream = new FileInputStream(file); OutputStream outputStream = response.getOutputStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } } else { // 文件不存在的处理逻辑 // 可以输出错误信息或者重定向到其他页面 } %> ``` 在上述代码,我们首先获取请求参数的文件名,然后构建文件的完整路径。接下来,我们检查文件是否存在,如果存在,则设置响应的Content-Type和Content-Disposition头信息。然后,使用InputStream读取文件内容,并使用OutputStream将文件内容写入响应输出流。 请注意,在上述代码,我们将文件路径设置为`path/to/files/`,你需要根据你的实际情况修改为正确的文件路径。 这样,当用户点击下载链接时,会触发download.jsp页面的执行,从而下载指定的文件到用户的本地计算机上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值