springboot文件下载
1.创建springboot项目,结构如下:
注意:为测试我们需要在webapp下download中自己添加一些文件
2. 代码部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; @Controller @RequestMapping ( "download" ) public class DownController { @RequestMapping ( "text" ) public String down(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println( "表单传来的名" +fileName); //获取文件地址 String realPath = request.getSession( true ).getServletContext().getRealPath( "download" ); //把服务器中文件读取到内存中 FileInputStream fis = new FileInputStream( new File(realPath,fileName)); //设置下载的类型 response.setHeader( "content-disposition" , "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8" )); //获取输出流 ServletOutputStream os = response.getOutputStream(); //复制 IOUtils.copy(fis,os); //关闭资源 fis.close(); os.close(); return null ; } } |
3. index.jsp
1 2 3 4 5 | <%@ page pageEncoding= "UTF-8" isELIgnored= "false" %> <a href= "${pageContext.request.contextPath}/download/text?fileName=a.txt" >a.txt</a> </br> <a href= "${pageContext.request.contextPath}/download/text?fileName=aa唐三.docx" >aa唐三.docx</a> |
4. pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <!--父级项目依赖--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version> 2.2 . 5 .RELEASE</version> </parent> <dependencies> <!--web支持的jar springboot的启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--JSP解析依赖--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!--war包--> <!--去掉内嵌tomcat--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!--去掉使用内嵌tomcat解析jsp--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies> |
5. application.properties
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
6.启动项目,访问项目接口 会跳转到 jsp页面
标签:
后端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了