SpringBoot2.1.x下实现文件的上传与下载

  1. 新建一个SpringBoot项目

  2. 引入相关的Maven依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
  3. 修改配置文件application.yml

    server:
      port: 8082
    
    spring:
      servlet:
        multipart:
          max-request-size: 10MB  #上传文件总的最大值
          max-file-size: 10MB     #单个文件的最大值
      mvc:
        view:
          prefix: templates
          suffix: .html
    
  4. 新建FileController用于文件的上传和下载

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    import org.springframework.web.servlet.mvc.support.RedirectAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.List;
    
    @Controller
    @RequestMapping("/api/v1/file")
    public class FileController {
    
        private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    
        private static final String filePath = "E:/project/springboot-filedownlowd-upload/src/main/resources/static/file/";
    
        /**
         * 单个文件上传页面跳转
         * @return
         */
        @GetMapping("upload")
        public String upload(){
            logger.info("====upload=====");
            return "upload";
        }
    
        /**
         * 上传单个文件
         * @param file
         * @param redirectAttributes
         * @return
         */
        @PostMapping("upload")
        public String upload(@RequestParam(value = "file") MultipartFile file, RedirectAttributes redirectAttributes){
            if(file.isEmpty()){
                return "文件上传失败,请重新选择文件";
            }
    
            String fileName = file.getOriginalFilename();
            File dest = new File(filePath + fileName);
    
            try {
                file.transferTo(dest);
                logger.info("文件上传成功");
                redirectAttributes.addAttribute("message","文件上传成功");
                return "redirect:/api/v1/file/upload";
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "文件上传失败";
        }
    
        /**
         * 多个文件上传页面跳转
         * @return
         */
        @GetMapping("multiupload")
        public String multi(){
            return "multiupload";
        }
    
        /**
         * 多个文件上传
         * @param request
         * @return
         */
        @PostMapping("multiupload")
        public String multi(HttpServletRequest request){
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
    
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
    
                if (file.isEmpty()) {
                    return "上传第" + (i++) + "个文件失败";
                }
                String fileName = file.getOriginalFilename();
                File dest = new File(filePath + fileName);
                try {
                    file.transferTo(dest);
                    logger.info("第" + (i + 1) + "个文件上传成功");
                } catch (IOException e) {
                    logger.error(e.toString(), e);
                }
            }
            return "multiupload";
        }
    
        /**
         * 文件下载页面跳转
         * @return
         */
        @GetMapping("download")
        public String download(){
            return "download";
        }
    
        /**
         * 文件下载
         * @param fileName
         * @param request
         * @param response
         * @return
         */
        @PostMapping("download")
        public String download(String fileName, HttpServletRequest request, HttpServletResponse response){
            response.setContentType("text/html;charset=utf-8");
    
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
    
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
    
            String downLoadPath = filePath + File.separator + fileName;  //注意不同系统的分隔符
    
            try {
                long fileLength = new File(downLoadPath).length();
                response.setContentType("application/x-msdownload;");
                response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
                response.setHeader("Content-Length", String.valueOf(fileLength));
                bis = new BufferedInputStream(new FileInputStream(downLoadPath));
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null)
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                if (bos != null)
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
            return null;
        }
    
    }
    
  5. 新增单个文件上传测试页面upload.html

    <!doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script type="application/javascript" src=""></script>
    
    
        <title>文件上传</title>
    </head>
    <body>
        <h4>单文件文件上传</h4>
    
        <form method="post" action="/api/v1/file/upload" enctype="multipart/form-data">
            <input type="file" name="file"><br>
            <input type="submit" value="提交">
        </form>
    
    </body>
    </html>
    
  6. 新增多个文件上传的测试页面multiupload.html

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <h4>多文件文件上传</h4>
    
        <form method="post" action="/api/v1/file/multiupload" enctype="multipart/form-data">
            <input type="file" name="file"><br>
            <input type="file" name="file"><br>
            <input type="file" name="file"><br>
            <input type="submit" value="提交">
        </form>
    </body>
    </html>
    
  7. 新增下载文件测试页面

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    
    
    </head>
    <body>
        <form id="download" action="/api/v1/file/download" method="post">
            文件名称: <input type="text" name="fileName" id="fileName"/>
            <div id="downDiv">
                <input id="downloadbtn" type="submit" value="下载文件">
            </div>
        </form>
    </body>
    </html>
    
  8. 分别访问 http://localhost:8082/api/v1/file/upload http://localhost:8082/api/v1/file/multiupload http://localhost:8082/api/v1/file/download 即可测试上述的单文件上传、多文件上传和文件下载的功能

  9. 详细代码见 SpringBoot下实现文件上传与下载

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值