29. Spring boot 文件上传(多文件上传)【从零开始学Spring Boot】

来源:互联网 发布:面包板是做单片机的吗 编辑:程序博客网 时间:2024/06/10 02:46

文件上传主要分以下几个步骤

(1)新建maven java project;

(2)在pom.xml加入相应依赖;

(3)新建一个表单页面(这里使用thymeleaf);

(4)编写controller;

(5)测试;

(6)对上传的文件做一些限制;

(7)多文件上传实现

(1)新建maven java project

新建一个名称为spring-boot-fileuploadmaven java项目;

 

(2)在pom.xml加入相应依赖;

加入相应的maven依赖,具体看以下解释:

<!--

              springboot父节点依赖,

             引入这个之后相关的引入就不需要添加version配置,

              springboot会自动选择最合适的版本进行添加。

        -->

       <parent>

              <groupId>org.springframework.boot</groupId>

              <artifactId>spring-boot-starter-parent</artifactId>

              <version>1.3.3.RELEASE</version>

       </parent>

 <dependencies>

          <!-- spring boot web支持:mvc,aop... -->

              <dependency>

                     <groupId>org.springframework.boot</groupId>

                     <artifactId>spring-boot-starter-web</artifactId>

              </dependency>

              <!-- thmleaf模板依赖. -->

              <dependency>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-starter-thymeleaf</artifactId>

              </dependency>

 </dependencies>

     <build>

              <plugins>

                     <!-- 编译版本; -->

                     <plugin>

                            <artifactId>maven-compiler-plugin</artifactId>

                            <configuration>

                                  <source>1.8</source>

                                  <target>1.8</target>

                            </configuration>

                     </plugin>

              </plugins>

       </build>

 

(3)新建一个表单页面(这里使用thymeleaf)

在src/main/resouces新建templates(如果看过博主之前的文章,应该知道,templates是spring boot存放模板文件的路径),在templates下新建一个file.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>

       <title>Hello World!</title>

   </head>

   <body>

      <form method="POST" enctype="multipart/form-data"action="/upload"> 

              <p>文件:<input type="file" name="file"/></p>

          <p><input type="submit" value="上传" /></p>

      </form>

   </body>

</html>

 

(4)编写controller;

       编写controller进行测试,这里主要实现两个方法:其一就是提供访问的/file路径;其二就是提供post上传的/upload方法,具体看代码实现:

package com.kfit;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

 

importorg.springframework.stereotype.Controller;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.RequestParam;

importorg.springframework.web.bind.annotation.ResponseBody;

importorg.springframework.web.multipart.MultipartFile;

 

@Controller

publicclass FileUploadController {

      

       //访问路径为:http://127.0.0.1:8080/file

       @RequestMapping("/file")

       public String file(){

              return"/file";

       }

      

       /**

        *文件上传具体实现方法;

        *@param file

        *@return

        */

       @RequestMapping("/upload")

       @ResponseBody

       public StringhandleFileUpload(@RequestParam("file")MultipartFilefile){

              if(!file.isEmpty()){

                     try {

                            /*

                             *这段代码执行完毕之后,图片上传到了工程的跟路径;

                             *大家自己扩散下思维,如果我们想把图片上传到 d:/files大家是否能实现呢?

                             *等等;

                             *这里只是简单一个例子,请自行参考,融入到实际中可能需要大家自己做一些思考,比如:

                             * 1、文件路径;

                             * 2、文件名;

                             * 3、文件格式;

                             * 4、文件大小的限制;

                             */

                            BufferedOutputStreamout =newBufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));

                            out.write(file.getBytes());

                            out.flush();

                            out.close();

                     }catch(FileNotFoundExceptione) {

                            e.printStackTrace();

                            return "上传失败,"+e.getMessage();

                     }catch (IOExceptione) {

                            e.printStackTrace();

                            return "上传失败,"+e.getMessage();

                     }

                     return "上传成功";

              }else{

                     return "上传失败,因为文件是空的.";

              }

       }

}

 

(5)编写App.java然后测试

       App.java没什么代码,就是Spring Boot的启动配置,具体如下:

package com.kfit;

 

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;

 

/**

 * Hello world!

 *

 */

//其中@SpringBootApplication申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan

@SpringBootApplication

publicclass App {

       publicstatic void main(String[]args) {

              SpringApplication.run(App.class,args);

       }

}

 

然后你就可以访问:http://127.0.0.1:8080/file进行测试了,文件上传的路径是在工程的跟路径下,请刷新查看,其它的请查看代码中的注释进行自行思考。

 

(6)对上传的文件做一些限制;

 

       对文件做一些限制是有必要的,在App.java进行编码配置:

@Bean 

   public MultipartConfigElement multipartConfigElement() { 

        MultipartConfigFactoryfactory = newMultipartConfigFactory();

        //// 设置文件大小限制 ,超了,页面会抛出异常信息,这时候就需要进行异常信息的处理了;

        factory.setMaxFileSize("128KB"); //KB,MB

        /// 设置总上传数据总大小

        factory.setMaxRequestSize("256KB"); 

        //Sets the directory location wherefiles will be stored.

        //factory.setLocation("路径地址");

        returnfactory.createMultipartConfig(); 

    } 

 

(7)多文件上传实现

       多文件对于前段页面比较简单,具体代码实现:

在src/resouces/templates/mutifile.html

<!DOCTYPEhtml>

<htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"

      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

   <head>

        <title>Hello World!</title>

   </head>

   <body>

      <formmethod="POST"enctype="multipart/form-data"action="/batch/upload"> 

             <p>文件1:<inputtype="file"name="file"/></p>

             <p>文件2:<inputtype="file"name="file"/></p>

             <p>文件3:<inputtype="file"name="file"/></p>

           <p><inputtype="submit"value="上传"/></p>

      </form>

   </body>

</html>

com.kfit.FileUploadController中新增两个方法:

/**

        *多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile

        *@param request

        *@return

        */

       @RequestMapping(value="/batch/upload", method=RequestMethod.POST

   public@ResponseBody 

   String handleFileUpload(HttpServletRequestrequest){ 

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

        MultipartFile file = null;

        BufferedOutputStream stream = null;

        for (inti =0; i< files.size(); ++i) { 

            file = files.get(i); 

            if (!file.isEmpty()) { 

                try

                    byte[]bytes = file.getBytes(); 

                    stream

                            newBufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename()))); 

                    stream.write(bytes); 

                    stream.close(); 

                } catch (Exceptione) { 

                       streamnull;

                    return"You failed to upload " + i + " =>" + e.getMessage(); 

                } 

            } else

                return"You failed to upload " + i + " becausethe file was empty."

            } 

        } 

        return"upload successful"

    } 

 

访问路径:http://127.0.0.1:8080/mutifile进行测试。


【Spring Boot 系列博客】

61. mybatic insert异常:BindingException: Parameter 'name' not found【从零开始学Spring B】 

 

 

60. Spring Boot写后感【从零开始学Spring Boot】 

 

 

59. Spring Boot Validator校验【从零开始学Spring Boot】 

 

58. Spring Boot国际化(i18n)【从零开始学Spring Boot】 

 

57. Spring 自定义properties升级篇【从零开始学Spring Boot】 

 

56. spring boot中使用@Async实现异步调用【从零开始学Spring Boot】 

 

55. spring boot 服务配置和部署【从零开始学Spring Boot】 

 

54. spring boot日志升级篇—logback【从零开始学Spring Boot】

 

52. spring boot日志升级篇—log4j多环境不同日志级别的控制【从零开始学Spring Boot】 

 

51. spring boot属性文件之多环境配置【从零开始学Spring Boot】

 

50. Spring Boot日志升级篇—log4j【从零开始学Spring Boot】

 

49. spring boot日志升级篇—理论【从零开始学Spring Boot】

 

48. spring boot单元测试restfull API【从零开始学Spring Boot】

 

47. Spring Boot发送邮件【从零开始学Spring Boot】

 

46. Spring Boot中使用AOP统一处理Web请求日志

 

45. Spring Boot MyBatis连接Mysql数据库【从零开始学Spring Boot】

 

44. Spring Boot日志记录SLF4J【从零开始学Spring Boot】

 

43. Spring Boot动态数据源(多数据源自动切换)【从零开始学Spring Boot】

 

42. Spring Boot多数据源【从零开始学Spring Boot】

 

41. Spring Boot 使用Java代码创建Bean并注册到Spring中【从零开始学Spring Boot】

 

40. springboot + devtools(热部署)【从零开始学Spring Boot】 

 

39.4 Spring Boot Shiro权限管理【从零开始学Spring Boot】

 

39.3 Spring Boot Shiro权限管理【从零开始学Spring Boot】

 

39.2. Spring Boot Shiro权限管理【从零开始学Spring Boot】

 

39.1 Spring Boot Shiro权限管理【从零开始学Spring Boot】

 

38 Spring Boot分布式Session状态保存Redis【从零开始学Spring Boot】 

 

37 Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】 

 

36 Spring Boot Cache理论篇【从零开始学Spring Boot】

 

35 Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】 

 

34Spring Boot的启动器Starter详解【从零开始学Spring Boot】

 

33 Spring Boot 监控和管理生产环境【从零开始学Spring Boot】

 

32 Spring Boot使用@SpringBootApplication注解【从零开始学Spring Boot】 

 

 

 

 

更多查看博客: http://412887952-qq-com.iteye.com/


1 0