1、前端
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="downLoadServlet">图片</a><br>
</body>
</html>
2、后台
package com.servlets;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//所有下载都以附件的形式
String filename = "图片.jpg";
//将字符串按照当前格式打散
byte[] bytes = filename.getBytes("utf-8");
//将打散的字节按照指定格式组装
filename = new String(bytes, "iso8859-1");
//修改响应头部属性content-disposition值为attachment
response.setHeader("content-disposition", "attachment;filename=" + filename);
//获取连接服务端资源文件输入流
InputStream is = this.getServletContext().getResourceAsStream("/resources/1.jpg");
//获取输出流
ServletOutputStream os = response.getOutputStream();
//将输入流中的数据写到输出流
int len = -1;
byte[] buffer = new byte[1024];
while((len = is.read()) != -1) {
os.write(buffer, 0, len);
}
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}