您的位置:首页 > 编程语言 > Java开发

Spring boot 文件上传(多文件上传)

2017-08-08 13:37 477 查看
1.加入相应的maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot</name>
<description>Demo project for Spring Boot</description>
<!--
spring boot 父节点依赖,
引入这个之后相关的引入就不需要添加version配置,
spring boot会自动选择最合适的版本进行添加。
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- spring boot web支持:mvc,aop... -->
<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>
<!--thymleaf模板-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

<build>
<plugins>
<!-- 编译版本; -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>


2.新建一个表单页面(这里使用thymleaf)
在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>


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

@Controller
public class FileUploadController {
//访问路径为:http://127.0.0.1:8080/file
@RequestMapping("/file")
public String file() {
return "/file";

}

/**
* 文件上传具体实现方法;
*
* @param file
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
/*
* 这段代码执行完毕之后,图片上传到了工程的跟路径;
* 大家自己扩散下思维,如果我们想把图片上传到 d:/files大家是否能实现呢?
* 等等;
* 这里只是简单一个例子,请自行参考,融入到实际中可能需要大家自己做一些思考,比如:
* 1、文件路径;
* 2、文件名;
* 3、文件格式;
* 4、文件大小的限制;
*/
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file
.getOriginalFilename())));
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
}
return "上传成功";
} else {

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

}
}
}


然后你就可以访问:http://127.0.0.1:8080/file 进行测试了,文件上传的路径是在工程的根路径下

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

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 设置文件大小限制 ,超了,页面会抛出异常信息,这时候就需要进行异常信息的处理了;
factory.setMaxFileSize("128KB"); //KB,MB
// 设置总上传数据总大小
factory.setMaxRequestSize("256KB");
//Sets the directory location where files will be stored.
//factory.setLocation("路径地址");
return factory.createMultipartConfig();
}
}


5.多文件上传实现
在src/resouces/templates/mutifile.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="/batch/upload">
<p>文件1:<input type="file" name="file" /></p>
<p>文件2:<input type="file" name="file" /></p>
<p>文件3:<input type="file" name="file" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>


/**
* 多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile
*
* @param request
* @return
*/
@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
public
@ResponseBody
String handleFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
stream.write(bytes);
stream.close();
} catch (Exception e) {
stream = null;
return "You failed to upload " + i + " => " + e.getMessage();
}
} else {
return "You failed to upload " + i + " because the file was empty.";
}
}
return "upload successful";
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: