一、单文件上传
1、在pom.xml加入相应依赖
<!-- thmleaf模板依赖. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- thmleaf模板依赖. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- thmleaf模板依赖. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、编写controller
package com.gongh.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class FileUploadController {
@RequestMapping("/file")
public String file(){
return"/file";
}
/**
* 文件上传具体实现方法;
* @param file
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file")MultipartFile file){
if(!file.isEmpty()){
try {
//获取文件名及后缀
String filename = file.getOriginalFilename();
String ext = filename.substring(filename.lastIndexOf("."));
System.out.print(filename+"---后缀---"+ext);
//改文件名称
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = sdf.format(new Date())+UUID.randomUUID()+ext;
//项目根路径
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath() +"/";
//文件存储路径
File savepath = new File(basePath +"static/uploadfile");
if (!savepath.exists()) {
savepath.mkdirs();
}
/*
* 图片上传到了工程的指定路径;
*/
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(basePath +"static/uploadfile/"+newFileName)));
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return"upload failed,"+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return"upload failed,"+e.getMessage();
}
return "upload success";
}else{
return"upload failed because the file is empty.";
}
}
}
3、在templates下新建一个file.html: 在src/main/resouces/templates(templates是spring boot存放模板文件的路径),
<!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>文件上传demo</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>
好啦,可以开始测试啦,打开浏览器,访问http://localhost:8080/file,选择文件进行上传。
二、多文件上传
1、对上传的文件做一些限制,在App.java进行编码配置:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//设置文件大小限制 ,超了,页面会抛出异常信息,这时候就需要进行异常信息的处理了;
factory.setMaxFileSize("1024KB"); //KB,MB
// 设置总上传数据总大小
factory.setMaxRequestSize("1024KB");
//factory.setLocation("路径地址");
return factory.createMultipartConfig();
}
2、编写多文件上传controller
package com.gongh.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
public class FileUploadController {
@RequestMapping("/multiuploadfile")
public String multiuploadfile(){
return"/multiuploadfile";
}
/**
* 多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile
* @param request
* @return
*/
@RequestMapping(value="/multiupload", method= RequestMethod.POST)
@ResponseBody
public 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";
}
}
3、编写multiuploadfile.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>多文件上传demo</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/multiupload">
<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>
好啦,可以开始测试啦,打开浏览器,访问http://localhost:8080/multiuploadfile,选择文件进行上传。