Springboot 配置跳转html + 文件的上传下载

1. 引入相关依赖, 重点是thymeleaf依赖
pom.xml

        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
2.在 application.properties 【src/main/resources】配置
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
3.html文件

这里写图片描述

fileUpload.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8" />
<title>fileUpload page</title>
</head>
<body>
    <h1 th:inlines="text">文件上传</h1>
    <form action="fileUpload" method="post" enctype="multipart/form-data">
        <p>选择文件: <input type="file" name="fileName"/></p>
        <p><input type="submit" value="提交"/></p>
    </form>
</body>
</html>

multifileUpload.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8" />
<title>multifileUpload page</title>
</head>
<body>
    <h1 th:inlines="text">文件上传</h1>
    <form action="multifileUpload" method="post" enctype="multipart/form-data" >
        <p>选择文件1: <input type="file" name="fileName"/></p>
        <p>选择文件2: <input type="file" name="fileName"/></p>
        <p>选择文件3: <input type="file" name="fileName"/></p>
        <p><input type="submit" value="提交"/></p>
    </form>
</body>
</html>
4.我这边是用文件上传的demo测试的,顺便把文件上传的controller代码也贴一下:

FileUploadController.java

package com.example.demo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller  //此处必须是@Controller,@RestController不行  
public class FileUploadController {
    private final static Logger logger = LoggerFactory.getLogger(MyController.class);

    /**
     http://ip:port/file
    */
    @RequestMapping("/file")
    public String file() {
        logger.info("单文件上传页面");
        return "/fileUpload";
    }

    /**
     http://ip:port/multifile
    */
    @RequestMapping("/multifile")
    public String multifile() {
        logger.info("多文件上传页面");
        return "/multifileUpload";
    }

    /**
     * 实现单文件上传
     *http://ip:port/fileUpload
     * */
    @RequestMapping("fileUpload")
    @ResponseBody 
    public String fileUpload(@RequestParam("fileName") MultipartFile file){
        if(file.isEmpty()){
            return "this file is empty";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = "F:/test" ;//文件保存路径
        File targetFile = new File(path + "/" + fileName);
        if(!targetFile.getParentFile().exists()){ //判断文件父目录是否存在
            targetFile.getParentFile().mkdir();
        }
        try {
            file.transferTo(targetFile); //保存文件
            return "upload file success";
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return "upload file fail";
        } catch (IOException e) {
            e.printStackTrace();
            return "upload file fail";
        }
    }

    /**
     * 实现多文件上传
     * http://ip:port/multifileUpload
     * */
    @RequestMapping(value="multifileUpload",method=RequestMethod.POST) 
    public @ResponseBody String multifileUpload(HttpServletRequest request){

        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");

        if(files.isEmpty()){
            return "this file is empty";
        }

        String path = "F:/test" ;

        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            if(file.isEmpty()){
                return "this file is empty";
            }else{        
                File targetFile= new File(path + "/" + fileName);
                if(!targetFile.getParentFile().exists()){ //判断文件父目录是否存在
                    targetFile.getParentFile().mkdir();
                }
                try {
                    file.transferTo(targetFile);
                }catch (Exception e) {
                    e.printStackTrace();
                    return "upload file fail";
                } 
            }
        }
        return "upload file success";
    }

    @RequestMapping("download")
    public String downLoad(HttpServletResponse response){
        String filename="test.jpg";
        String filePath = "F:/test" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file); 
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("file download:  " + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
5.访问

multifileUpload
uploadsuccess

猜你喜欢

转载自blog.csdn.net/try_try_try/article/details/80257583