首页 > 其他分享 >29. Spring boot 文件上传(多文件上传)【从零开始学Spring Boot】

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

时间:2023-07-03 14:31:45浏览次数:43  
标签:文件 java Spring boot springframework file return 上传

文件上传主要分以下几个步骤:
(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、文件大小的限制;
                             */
out =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 {
       publicstaticvoid main(String[]args) {
              SpringApplication.run(App.class,args);
       }
}
 
然后你就可以访问:http://127.0.0.1:8080/file进行测试了,文件上传的路径是在工程的跟路径下,请刷新查看,其它的请查看代码中的注释进行自行思考。
 
(6)对上传的文件做一些限制;
 
       对文件做一些限制是有必要的,在App.java进行编码配置:
@Bean
   public MultipartConfigElement multipartConfigElement() { 
factory =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
request){ 
 files =((MultipartHttpServletRequest)request).getFiles("file"); 
 file = null;
 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) { 
 stream =  null;
                    return"You failed to upload " +i + " =>" +e.getMessage();  
                }  
            } else { 
                return"You failed to upload " +i + " becausethe file was empty."; 
            } 
        } 
        return"upload successful"; 
    }

标签:文件,java,Spring,boot,springframework,file,return,上传
From: https://blog.51cto.com/u_11142439/6611296

相关文章

  • springboot下的@NotBlank,@NotNull,@NotEmpty
    话不多说1.三个注解区别@NotBlank只能作用在String上,不能为null,而且调用trim()后,长度必须大于0(不能为空格)@NotNull不能为null,但可以为空字符串,校验Integer类型不能为空@NotEmpty不能为null,并且长度必须大于0,校验List类型不能为空2.依赖引入`<dependency> ......
  • JAVA生成xml文件格式
    publicboolean A(参数1,……){Documentdocument=DocumentHelper.createDocument();Namespacena=Namespace.get("");Strings=null;na=new Namespace(xxxxxxxxxxxxxxxxxxxxx);//命名空间Elementroot=document.addElement(newQName(“A......
  • 文件权限
    linux文件权限一、linux文件权限1、权限关联对象u#ower属主g#group属组o#other其他a#all所有人2、文件权限字母表示r#Read读w#Write写x#Execute执行3、权限数字表示r——4w——2x——14、linux文件类型文件属性文件类型......
  • Apache FtpServer Spring3 整合
    配置运行成功,以备遗忘。Spring配置当中加入 <importresource="applicationFTP.xml"/>在Spring配置同级目录创建 applicationFTP.xml<?xmlversion="1.0"encoding="UTF-8"?><serverxmlns="http://mina.apache.org/ftpserver/spring/v1"  ......
  • 基于 Spring Cloud Function 的 Azure Function 开发
    Notice:本文章不包含AzureFunction环境配置等内容1.1前提Azure账户,且有可使用的订阅Azure支持的JDK(本教程适用于JDK1.8)IntelliJIDEA社区版或无限制版均可Maven3.5+最新的FunctionCoreTools1.2创建SpringCloudFunctionAzure工程在Github仓......
  • elementui 手动上传文件 post 请求
    //上传图片校验  fileChange(file){   constisJPG=file.raw.type==='image/jpeg'   constisPNG=file.raw.type==='image/png'   constisLt2M=file.raw.size/1024/1024<0.2   if(!isPNG&&!isJPG){   ......
  • Oracle-控制文件成员
    为保证数据库安全,防止因为控制文件损坏而造成实例崩溃CRASH,增加一个控制文件成员,并存放于不同于当前的ASM磁盘上,以备不时之需。1.增加一组控制文件参数[RAC01]注:第2个控制文件只需要指定到其他ASM磁盘组,+DATA为原控制文件所在ASM磁盘组。SQL>setlines999pages999showparam......
  • springboot自动装配
    1、自动装配是什么及作用springboot的自动装配实际上就是为了从spring.factories文件中获取到对应的需要进行自动装配的类,并生成相应的Bean对象,然后将它们交给spring容器来帮我们进行管理2、spring自动装配的原理2.1、启动类上注解的作用@SpringBootApplication这个注解是spri......
  • springboot框架介绍,让我们深入的了解
    ​ SpringBoot是一种用于快速构建基于Spring框架的Java应用程序的开源框架。它旨在简化Spring应用程序的开发过程,通过提供一种约定优于配置的方式,让开发人员能够快速搭建起一个可独立运行的、可部署的、易于扩展的应用。SpringBoot内置了许多开箱即用的功能和插件,使得开发者......
  • 聊聊Excel解析:如何处理百万行EXCEL文件
    一、引言Excel表格在后台管理系统中使用非常广泛,多用来进行批量配置、数据导出工作。在日常开发中,我们也免不了进行Excel数据处理。那么,如何恰当地处理数据量庞大的Excel文件,避免内存溢出问题?本文将对比分析业界主流的Excel解析技术,并给出解决方案。如果这是您第一次接触Excel......