import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value="/download")
public class Download extends HttpServlet {
@RequestMapping(value="download1")
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取文件下载路径
String path = req.getServletContext().getRealPath("/").replace("\\", "/");
String filename = req.getParameter("filename");
File file = new File(path +"images"+"\\"+ filename);
if(file.exists()){
//设置相应类型application/octet-stream
resp.setContentType("application/x-msdownload");
//设置头信息
resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
InputStream inputStream = new FileInputStream(file);
ServletOutputStream ouputStream = resp.getOutputStream();
byte b[] = new byte[1024];
int n ;
while((n = inputStream.read(b)) != -1){
ouputStream.write(b,0,n);
}
//关闭流、释放资源
ouputStream.close();
inputStream.close();
}else{
req.setAttribute("errorResult", "文件不存在下载失败!");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/a.jsp");
dispatcher.forward(req, resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}
<%@ 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="download/download1?filename=a.jpg">下载文件</a>${errorResult}
</body>
</html>
最近在整理一些资源工具,放在网站分享 http://tools.maqway.com 欢迎关注公众号:麻雀唯伊 , 不定时更新资源文章,生活优惠,或许有你想看的