Java教程

springboot文件下载

本文主要是介绍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文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!