springboot(七)文件上传与下载

x33g5p2x  于2021-12-17 转载在 其他  
字(8.2k)|赞(0)|评价(0)|浏览(383)

springboot实现单文件、多文件上传与文件下载

      新建项目:springboot-file,打开pom.xml文件加入相关依赖

<dependencies>
		<!--web-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
    	<!--thymeleaf模板引擎-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

 配置application.properties,内容如下:

#单个数据的大小
spring.servlet.multipart.max-file-size = 100Mb
#总数据的大小
spring.servlet.multipart.max-request-size=100Mb

 :如果不配置单个数据大小,springboot默认的上传文件的大小为1MB,大于这个值就会报错。

编写文件配置类:FileConfig.java

public class FileConfig {
    //对应的上传目录
    public static final String UPLOAD_PATH = "D:/img/";
    //允许上传的图片格式
    public static  final String[] UPLOAD_IMAGE_TYPES = {"jpg","ico","gif","png"};
    //允许上传的文件格式
    public static final  String[] UPLOAD_FILE_TYPES ={"doc","docx","xls","xlsx","txt"};
    //保存文件
    public  static final  long FILE_MAX_SIZE = 3L * 1024 * 1024;
}

编写控制器:FileController.java

@Controller
public class FileController {

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    /**
     *  单文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String fileUpload(@RequestParam("fileName") MultipartFile file) {
        //判断文件是否为空
        if (file.isEmpty()) {
            return "空文件";
        }
        if (file.getSize() > FileConfig.FILE_MAX_SIZE) {
            return "文件超过指定大小";
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
        //文件格式判断
        if (!Arrays.asList(FileConfig.UPLOAD_IMAGE_TYPES).contains(type.toLowerCase())
                && !Arrays.asList(FileConfig.UPLOAD_FILE_TYPES).contains(type.toLowerCase())) {
            return "图片类型不对";
        }
        //加入当前时间重命名文件,尽量避免文件名称重复
        String path = FileConfig.UPLOAD_PATH + new SimpleDateFormat("yyyyMMddHHmmss").
                format(new Date()) + "_" + fileName;
        File file1 = new File(path);
        //判断文件是否已经存在
        if (file1.exists()) {
            return "文件已存在";
        }
        //判断文件父目录是否存在
        if (!file1.getParentFile().exists()) {
            file1.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(file1);
        } catch (IOException e) {
            return "上传文件失败";
        }
        return path;
    }

    /**
     * 多文件上传
     * @param request
     * @return
     */
    @PostMapping("/uploads")
    @ResponseBody
    public Map<String, String> fileUploads(HttpServletRequest request){
        Map<String,String> map=new HashMap<String,String>();
        //fileNames为页面的文件控件的name
        List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("fileNames");
        for (MultipartFile file:files) {
            //获取文件名
            String fileName = file.getOriginalFilename();
            if (!file.isEmpty()) {
                if (file.getSize() > FileConfig.FILE_MAX_SIZE) {
                    map.put(fileName,"文件超过指定大小");
                    continue;
                }
                //获取文件后缀
                String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
                //文件格式判断
                if (!Arrays.asList(FileConfig.UPLOAD_IMAGE_TYPES).contains(type.toLowerCase())
                        && !Arrays.asList(FileConfig.UPLOAD_FILE_TYPES).contains(type.toLowerCase())) {
                    map.put(fileName,"图片类型不对");
                    continue;
                }
                //加入当前时间重命名文件,尽量避免文件名称重复
                String path = FileConfig.UPLOAD_PATH + new SimpleDateFormat("yyyyMMddHHmmss").
                        format(new Date()) + "_" + fileName;
                File file1 = new File(path);
                //判断文件是否已经存在
                if (file1.exists()) {
                    map.put(fileName,"文件已存在");
                    continue;
                }
                //判断文件父目录是否存在
                if (!file1.getParentFile().exists()) {
                    file1.getParentFile().mkdir();
                }
                try {
                    //保存文件
                    file.transferTo(file1);
                } catch (IOException e) {
                    map.put(fileName,"上传文件失败");
                }
            } else {
                map.put(fileName,"空文件");
            }
        }

       return map;

    }

    /**
     * 文件下载
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/download")
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        // 生成的文件名
        String fileName = "a.jpg";
        if (fileName != null) {
            //设置文件路径
            File file = new File(FileConfig.UPLOAD_PATH+fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                // 设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}

在/resouces/templates/下编写页面文件:index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>$Title$</title>
</head>
<body>

<p>-----------------------------------单文件上传-----------------------------------</p>
<form action="upload" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="fileName"/></p>
    <p><input type="submit" value="提交"/></p>
</form>

<p>-----------------------------------多文件上传-----------------------------------</p>
<form action="uploads" method="post" enctype="multipart/form-data">
    <p>选择文件1: <input type="file" name="fileNames"/></p>
    <p>选择文件2: <input type="file" name="fileNames"/></p>
    <p><input type="submit" value="提交"/></p>
</form>

<p>-----------------------------------文件下载-----------------------------------</p>
<a href="/download">文件下载</a>

</body>
</html>

**注:**1.html文件中要使用thymeleaf语法,得加入<html xmlns:th="http://www.thymeleaf.org">

       2. thymeleaf默认得模板配置文件位置在/resouces/templates/下,所以我们使用默认得,application.properties配置文件中就不用管啦

       3. 多文件上传中我返回一个map,如果map中有键值对数据,键代表文件名称,值代表提示的信息。

       

测试访问:ip:端口/index,文件上传下载到此结束!

最后,封装了一个文件工具类,用的上得可以瞅瞅哦!

public class FileUtils {

    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    public static File base64ToFile(String base64) {
        File file = null;
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file = new File(formatDate() + "base64ToFile.png");
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    //删除文件
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            file.delete();
            return true;
        }
        return false;

    }

    //清空文件夹
    public static boolean deleteDir(String path) {
        File file = new File(path);
        //判断是否待删除目录是否存在
        if (!file.exists()) {
            System.err.println("The dir are not exists!");
            return false;
        }
        //取得当前目录下所有文件和文件夹
        String[] content = file.list();
        for (String name : content) {
            File temp = new File(path, name);
            //判断是否是目录
            if (temp.isDirectory()) {
                //递归调用,删除目录里的内容
                deleteDir(temp.getAbsolutePath());
                //删除空目录
                temp.delete();
            } else {
                //直接删除文件
                if (!temp.delete()) {
                    System.err.println("Failed to delete " + name);
                }
            }
        }
        return true;
    }

    public static String formatDate() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    public static void main(String[] args) {
//        System.out.println(deleteFile("G:/test/test.txt"));
//        File file = new File("D:/img/a.jpg");
//        String fileToBase64 = fileToBase64(file);
//        System.out.println(fileToBase64);
//
//        File file1 = base64ToFile(fileToBase64);
//        System.out.println(file1.getName());
    }
}

源码地址https://gitee.com/xu0123/springboot2

相关文章