【Spring boot 文件上传】

Spring boot 文件上传
文件上传主要分以下几个步骤:
(1)新建 maven java project;
(2)在 pom.xml 加入相应依赖;
(3)新建一个表单页面(这里使用 thymleaf);
(4)编写 controller;
(5)测试;
(6)对上传的文件做一些限制;
(7)多文件上传实现
(1)新建 maven java project
新建一个名称为 spring-boot-fileupload maven java 项目;
(2)在 pom.xml 加入相应依赖;
加入相应的 maven 依赖,具体看以下解释:
POM.XML
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = " http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd " >
< modelVersion > 4.0.0 modelVersion >
< groupId > com.hpit groupId >
< artifactId > springboot03 artifactId >
< packaging > war packaging >
< version > 0.0.1-SNAPSHOT version >
< name > springboot03 Maven Webapp name >
< url > http://maven.apache.org url >
< properties >
< project.build.sourceEncoding > UTF-8 project.build.sourceEncoding >
properties >
< parent >
< groupId > org.springframework.boot groupId >
< artifactId > spring-boot-starter-parent artifactId >
< version > 1.4.0.RELEASE version >
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 > org.springframework.boot groupId >
< artifactId > spring-boot-configuration-processor artifactId >
< optional > true optional >
dependency >
< dependency >
< groupId > javax.servlet groupId >
< artifactId > javax.servlet-api artifactId >
< scope > provided scope >
dependency >
< dependency >
< groupId > log4j groupId >
< artifactId > log4j artifactId >
< version > 1.2.17 version >
dependency >
< dependency >
< groupId > javax.servlet groupId >
< artifactId > jstl artifactId >
dependency >
< dependency >
< groupId > org.springframework.boot groupId >
< artifactId > spring-boot-starter-tomcat artifactId >
< scope > provided scope >
dependency >
< dependency >
< groupId > org.apache.tomcat.embed groupId >
< artifactId > tomcat-embed-jasper artifactId >
< scope > provided scope >
dependency >
dependencies >
< build >
< finalName > ${project.artifactId} finalName >
< directory > target directory >
< plugins >
< plugin >
< artifactId > maven-compiler-plugin artifactId >
< configuration >
< source > 1.8 source >
< target > 1.8 target >
configuration >
plugin >
plugins >
build >
project >
(3)新建一个表单页面(这里使用 thymleaf)
在 src/main/resouces 新建 templates(参照前面的章节,应该知道,templates 是 spring boot 存放模板文件的路
径),在 templates 下新建一个 file.html:
DOCTYPE html>
< html >
< head >
< title > spring boot 文件上传 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 方法,具体看代码实现:
com.hpit.springboot03.web.FileUploadController
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.log4j.Logger;
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;
/**
* TODO 文件上传控制器
*
*
*/
@Controller
public class FileUploadController {
private Logger logger = Logger. getLogger (getClass());
@RequestMapping (value = "/upload" , method = RequestMethod. GET )
public String file() {
logger .info( "跳转文件上传控制器" );
return "file" ;
}
/**
* TODO 文件上传控制器
*
* @param file
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping (value = "/upload" , method = RequestMethod. POST )
public String upload( @RequestParam ( "file" ) MultipartFile file ) throws IOException { // 文件上传
BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream( new File( file .getOriginalFilename())));
logger .info( "文件名称:
" + file .getOriginalFilename());
outputStream .write( file .getBytes());
outputStream .flush();
outputStream .close();
return "文件上传成功" ;
}
}
(5)编写 App.java 然后测试
App.java 没什么代码,就是 Spring Boot 的启动配置,具体如下:
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ServletComponentScan // 开始servlet扫描
@ComponentScan (basePackages = { "com.hpit" })
public class App {
public static void main(String[] args ) throws Exception {
SpringApplication. run (App. class , args );
}
}
然后你就可以访问: http://127.0.0.1 /upload 进行测试了,文件上传的路径是在工程的跟路径下,请刷新查看,
其它的请查看代码中的注释进行自行思考。
【Spring boot 文件上传】_第1张图片

6 )对上传的文件做一些限制;
对文件做一些限制是有必要的,在 App.java 进行编码配置:
在 App 主程序入口处添加如下配置:
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ServletComponentScan // 开始servlet扫描
@ComponentScan (basePackages = { "com.hpit" })
public class App {
public static void main(String[] args ) throws Exception {
SpringApplication. run (App. class , args );
}
// 配置文件上传
@Bean
public MultipartConfigElement multipartConfigFactory() {
MultipartConfigFactory configFactory = new MultipartConfigFactory();
configFactory .setMaxFileSize( "128MB" ); // KB MB 设置单个上传文件大小
configFactory .setMaxRequestSize( "1024MB" );
configFactory .setLocation( "/" ); // 设置文件上传路径
return configFactory .createMultipartConfig();
}
}
(7)多文件上传实现
多文件对于前段页面比较简单,具体代码实现:
在 src/main/resource 下面创建 multifile.html
DOCTYPE html>
< html >
< head >
< title > spring boot 多文件上传 title >
head >
< body >
< form method = "POST" enctype = "multipart/form-data" action = "/upload" >
< p >
文件1: < input type = "file" name = "file" />
文件2: < input type = "file" name = "file" />
文件3: < input type = "file" name = "file" />
p >
< p >
< input type = "submit" value = "上传" />
p >
form >
body >
html >
添加控制实现:com.hpit.springboot03.web.MultiFileUploadController
package com.hpit.springboot03.web;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class MultiFileUploadController {
private Logger logger = Logger. getLogger (getClass());
@RequestMapping (value = "/multifileupload" , method = RequestMethod. GET )
public String multiFile() {
logger .info( "跳转多文件上传" );
return "multifile" ;
}
/**
* TODO 多文件上传控制器
*
* @param servletRequest
* @return
*/
@RequestMapping (value = "multifileupload" , method = RequestMethod. POST )
public @ResponseBody String upload(HttpServletRequest servletRequest ) {
List files = ((MultipartHttpServletRequest) servletRequest ).getFiles( "file" );
for (MultipartFile multipartFile : files ) {
try {
BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream( new File( multipartFile .getOriginalFilename())));
outputStream .write( multipartFile .getBytes());
outputStream .flush();
outputStream .close();
} catch (FileNotFoundException e ) {
e .printStackTrace();
return "文件上传失败" ;
} catch (IOException e ) {
e .printStackTrace();
return "文件上传失败" ;
}
}
return "文件上传成功" ;
}
}
启动浏览器输入路径进行测试。
项目结构图
【Spring boot 文件上传】_第2张图片

你可能感兴趣的:(Spring,springboot,java,maven,spring,boot)