Springboot 之 多文件上传-知识林

来源:互联网 发布:魏无羡捏脸数据 编辑:程序博客网 时间:2024/04/18 19:35

本文章来自【知识林】

文件上传在各种网站平台上应用都非常广泛,这篇文章将讲述在Springboot中是如何完成文件上传的,Springboot是打包运行的,上传后的文件又该何去何从?

这篇文章需要用到前面所讲的知识点《Springboot 之 静态资源路径配置》和Thymeleaf相关的知识。

  • pom.xml
<parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.4.0.RELEASE</version>    <relativePath/> <!-- lookup parent from repository --></parent><dependencies>    <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>    <dependency>        <groupId>commons-io</groupId>        <artifactId>commons-io</artifactId>        <version>2.4</version>    </dependency></dependencies>

说明:页面模板还是使用Thymeleaf,文件上传工具使用Apache的commons-io

  • application.properties

此配置可参考《Springboot 之 静态资源路径配置》

server.port=1117spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.htmlspring.thymeleaf.cache=falseweb.upload-path=D:/temp/upload/study17/spring.mvc.static-path-pattern=/**spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\  classpath:/static/,classpath:/public/,file:${web.upload-path}
  • Controller控制器
@Controllerpublic class IndexController {    //获取上传的文件夹,具体路径参考application.properties中的配置    @Value("${web.upload-path}")    private String uploadPath;    /**     * GET请求     * 上传页面,也将显示已经存在的文件     * @param model     * @return     */    @GetMapping(value = "/index")    public String index(Model model) {        //获取已存在的文件        File [] files = new File(uploadPath).listFiles();        model.addAttribute("files", files);        return "web/index";    }    /**     * POST请求     * @param request     * @param files     * @return     */    @PostMapping(value = "index")    public String index(HttpServletRequest request, @RequestParam("headimg")MultipartFile[] files) {        //可以从页面传参数过来        System.out.println("name====="+request.getParameter("name"));        //这里可以支持多文件上传        if(files!=null && files.length>=1) {            BufferedOutputStream bw = null;            try {                String fileName = files[0].getOriginalFilename();                //判断是否有文件且是否为图片文件                if(fileName!=null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {                    //创建输出文件对象                    File outFile = new File(uploadPath + "/" + UUID.randomUUID().toString()+ getFileType(fileName));                    //拷贝文件到输出文件对象                    FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);                }            } catch (Exception e) {                e.printStackTrace();            } finally {                try {                    if(bw!=null) {bw.close();}                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return "redirect:/index";    }    /**     * 判断文件是否为图片文件     * @param fileName     * @return     */    private Boolean isImageFile(String fileName) {        String [] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};        if(fileName==null) {return false;}        fileName = fileName.toLowerCase();        for(String type : img_type) {            if(fileName.endsWith(type)) {return true;}        }        return false;    }    /**     * 获取文件后缀名     * @param fileName     * @return     */    private String getFileType(String fileName) {        if(fileName!=null && fileName.indexOf(".")>=0) {            return fileName.substring(fileName.lastIndexOf("."), fileName.length());        }        return "";    }}

说明: @RequestParam("headimg")MultipartFile[] files这里的headimg是根据页面上File inputname属性而定。

  • index.html
<!DOCTYPE html><html lang="zh-CN"      xmlns="http://www.w3.org/1999/xhtml"      xmlns:th="http://www.thymeleaf.org">    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>        <title>文件上传</title>    </head>    <body>        <h2>已有文件:</h2>        <p th:each="file : ${files}">            [站外图片上传中……(2)],文件名称:<span th:text="${file.name}"></span>        </p>        <hr/>        <form method="post" enctype="multipart/form-data">            昵称:<input name="name" type="text"/>            <br/>            头像:<input name="headimg" type="file"/>            <br/>            <button type="submit">确定上传</button>        </form>    </body></html>

注意:<input name="headimg" type="file"/>这里的headimg决定了Controller中@RequestParam("headimg")的值。如果有多个<input name="headimg" type="file"/>将是多文件上传。

  • 页面截图

通过上面例子上传两张图片后的效果:

多文件上传-知识林

示例代码:https://github.com/zsl131/spring-boot-test/tree/master/study17

本文章来自【知识林】

0 0
原创粉丝点击