springboot文件下载
2022/7/13 23:24:33
本文主要是介绍springboot文件下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.创建springboot项目,结构如下:
2. 代码部分
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
<%@ 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
<!--父级项目依赖--> <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
这篇关于springboot文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-20测试人员都是画画大神,让我看看谁还不会用代码图?
- 2024-05-20年薪百万的程序员都在用的摸鱼方式……
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了