前端代码:
// 一个用于点击的下载链接,你希望下载的时候显示什么文件名和格式,你就在参数上填什么
<a href='../FileDownloadServlet?fileName=Excel模板.xlsx' >下载Excel模板</a>
依赖文件:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.9</version>
</dependency>
后端代码:
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
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;
import java.io.IOException;
@WebServlet(value = "/FileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String path = "D:/fileupload/file/Template/";
String fileName = request.getParameter("fileName");
ServletOutputStream outputStream = response.getOutputStream();
byte[] bytes = FileUtil.readBytes(path + fileName);
response.setContentType("application/octet-stream");
fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
outputStream.write(bytes);
IoUtil.close(outputStream);
}
}
最后的效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6cae8d824abf1c48c498a35e21413b53.png)