前提:
1--新建一个Dynamic Web Project项目
2--将项目部署到tomcat
两步:
1--新建一个jsp文件-->download.jsp,内容如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href = "DownLoadFileServlet?fileName=总javascript.txt">
java知识的总结
</a>
</body>
</html>
2--创建servlet文件-->DownLoadFileServlet.java,内容如下
package com.icss.restrant.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
/**
* Servlet implementation class DownLoadFileServlet
*/
@WebServlet("/DownLoadFileServlet")
public class DownLoadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DownLoadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取要下载的文件名
String fileName = request.getParameter("fileName");
//2.实例化组件
SmartUpload smartUpload = new SmartUpload();
//3。初始化组件
smartUpload.initialize(getServletConfig(),request,response);
//4。设定setContentDisposition为null以禁止浏览器自动打开文件,保证单机链接是下载
smartUpload.setContentDisposition(null);
//5.下载
try {
smartUpload.downloadFile("E:/"+fileName);
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
需要自己写的代码用大字体标出总javascript.txt是我要下载的文件名,"E:/"是文件存放路径
最后,发布执行。。。